0

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;
  }
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 2
    Define the callbacks as arrow functions `img.onload = () => { ... }`. – ConnorsFan Mar 26 '18 at 21:19
  • read up on lambdas (fat arrow functions) and execution scope in javascript... can be tough to wrap your head around at first.. but it's not that difficult... best way to learn... get screwed a few times like this :) – a2345sooted Mar 27 '18 at 04:17
  • Thank you. I thought i would go insane.. –  Mar 27 '18 at 11:05

0 Answers0