Angular 2 call setInterval() undefined Services form Dependency injection

别等时光非礼了梦想. 提交于 2019-12-22 01:26:25

问题


I want to call a function every 10 minutes by using setInterval() and in this function I want to use a Service (called auth) that I get from the Dependency Injector of Angular 2, the problem is that the console tells me following:

EXCEPTION: TypeError: this.auth is undefined

  constructor(private auth: AuthService){
    setInterval(function(){ this.auth.refreshToken(); }, 1000 * 60 * 10);
  }

回答1:


this in the function given to setInterval doesn't point to the class when it is called.

Use arrow function instead.

 constructor(private auth: AuthService){
    setInterval(() => { this.auth.refreshToken(); }, 1000 * 60 * 10);
  }



回答2:


A full discussion of this issue can be found in the documentation for the setInterval() method, captioned The "this" Problem. About halfway down the page.

The jist is that it is the result of a change in the "this" variable. The function being passed into the setInterval() function is extracted from the class context and placed into the context of setInterval() (the window). So, it is undefined.

There are several solutions to this issue. The method proposed by toskv above is a fairly common approach. Another solution is to use the bind() method.

constructor(private auth: AuthService) {
    setInterval(this.auth.refreshToken.bind(this), 1000 * 60 * 10);
}

Reference material from this question, answer by Pointy.

Documentation for the bind() method.

A good article on javascript scope, which can still come back to bite you in typescript.




回答3:


There's a little trick for solving that. Hope this helps.

First do

const this1 = this;

then

constructor(private auth: AuthService) {
    setInterval(this1.auth.refreshToken.bind(this), 1000 * 60 * 10);
}


来源:https://stackoverflow.com/questions/35828830/angular-2-call-setinterval-undefined-services-form-dependency-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!