Angular 2 call setInterval() undefined Services fo

2019-04-18 04:28发布

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);
  }

3条回答
萌系小妹纸
2楼-- · 2019-04-18 05:09

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楼-- · 2019-04-18 05:15

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);
  }
查看更多
Ridiculous、
4楼-- · 2019-04-18 05:25

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);
}
查看更多
登录 后发表回答