0

I'm building an angular app for the first time and I've got a controller which is used to monitor the health of a system. The health data comes from a rest api which I can hit and get the data successfully. I want to set this up to run every 5 minutes using setInterval. I can call the function once immediately to get the initial data but when the interval fires, I continue to get the error "Uncaught TypeError: Cannot read property 'one' of undefined". I believe I'm facing an out of scope situation but can't for the life of me figure out how to fix it. Here's the code:

class SystemHealthController {
  /*@ngInject*/
  constructor($scope, $interval, Rest) {
    this.name = 'systemHealth';
    this.$scope = $scope;
    this.Rest = Rest;
    this.getHealth();
    setInterval(this.getHealth, 300000);
  }

  getHealth(){
     this.Rest.one('getHealth.html?system=10021').get().then((response) => {
        this.health = response;
        console.log(this.health);
    });
  }
}

export default SystemHealthController;
Eyowzitgoin
  • 129
  • 2
  • 12
  • Why do you need `this.Rest` in the first place and not just use `Rest`? Also `this` has different context inside callbacks – charlietfl Jun 14 '16 at 23:46
  • 1
    Without saving `Rest` into `this`, the first attempt to call `getHealth()` will fail because `Rest` is 'not defined'. I won't even make it to the interval without saving it off. The second part of your comment is where I believe I'm messing up but can't get my head wrapped around it. Expounding on this or giving some code example may be just the answer I'm looking for. – Eyowzitgoin Jun 14 '16 at 23:53
  • 2
    See http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback – charlietfl Jun 14 '16 at 23:56
  • That was absolutely the answer I needed, I just wasn't finding that based on what I thought was the problem. Post up an answer referring to `this` being not bound correctly in the callback and I will accept it! – Eyowzitgoin Jun 15 '16 at 00:04

0 Answers0