I want to check if a server is reachable on init of an angular element. I have a function like this:
export class AppComponent implements OnInit {
dataServerOffline: boolean = true;
constructor() {
}
ngOnInit() {
var img = document.body.appendChild(document.createElement("img"));
img.style.display = "none";
img.src = "http://myUrl.com/online.jpeg";
img.onload = function () {
// I know that this variable is not accessible form here.
this.dataServerOffline = false;
};
img.onerror = function () {
this.dataServerOffline = true;
};
}
No matter what I try, at the end "dataServerOffline" is undefined. How would I go about changing "dataServerOffline" inside of the "onload" and "onerror" functions?
I have already tried something like this:
export class AppComponent implements OnInit {
dataServerOffline: boolean = true;
constructor() {
}
ngOnInit() {
var temp;
var img = document.body.appendChild(document.createElement("img"));
img.style.display = "none";
img.src = "http://myUrl.com/online.jpeg";
img.onload = function () {
temp = false;
};
img.onerror = function () {
temp = true;
};
this.dataServerOffline = temp;
}