Angular 2 调用 setInterval() undefined 服务形式依赖注入

Angular 2 call setInterval() undefined Services form Dependency injection

我想使用 setInterval() 每 10 分钟调用一个函数,在这个函数中我想使用从依赖注入器获得的服务(称为 auth) Angular 2,问题是控制台告诉我以下内容:

EXCEPTION: TypeError: this.auth is undefined

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

this 在调用 setInterval 的函数中没有指向 class。

改用箭头函数。

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

此问题的 full discussion 可以在 setInterval() 方法的文档中找到,标题为 "this" 问题。大约在页面的一半。

要点是它是 "this" 变量变化的结果。传递给 setInterval() 函数的函数是从 class 上下文中提取的,并放入 setInterval() 的上下文中(window)。所以,它是未定义的。

这个问题有多种解决方案。上面toskv提出的方法是一种相当普遍的做法。 另一种解决方案是使用 bind() 方法。

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

参考 this question 中的 material,Pointy 的回答。

bind() method 的文档。

一篇关于 javascript scope 的好文章,它仍然可以用打字稿来咬你一口。

有一个小技巧可以解决这个问题。希望这有帮助。

先做

const this1 = this;

然后

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