Angular 2调用setInterval()undefined服务表单依赖注入

Ale*_*lex 21 setinterval typescript angular

我想通过使用setInterval()每隔10分钟调用一个函数,并且在这个函数中我想使用从Angular 2的Dependency Injector获得的Service(称为auth),问题是控制台告诉我以下内容:

EXCEPTION:TypeError:this.auth未定义

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

tos*_*skv 64

在给setInterval的函数被调用时不指向类.

请改用箭头功能.

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

  • 关于这个主题的优秀文章:http://www.2ality.com/2012/04/arrow-functions.html (3认同)

Kha*_*ore 6

一个充分讨论这个问题可以为setInterval()方法的文档中找到,标题的"本"的问题.大约在页面的一半.

问题在于它是"this"变量变化的结果.传递给setInterval()函数的函数从类上下文中提取并放入setInterval()(窗口)的上下文中.所以,它是未定义的.

这个问题有几种解决方案.上面的toskv提出的方法是一种相当常见的方法.另一种解决方案是使用bind()方法.

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

来自这个问题的参考资料,由Pointy回答.

bind()方法的文档.

一篇关于javascript范围的好文章,它仍然可以让你在打字稿中咬你.