Angular 2调用setInterval()未定义服务形式依赖注入 [英] Angular 2 call setInterval() undefined Services form Dependency injection
本文介绍了Angular 2调用setInterval()未定义服务形式依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过使用 setInterval()每10分钟调用一个函数,在这个函数中,我想使用从Angular 2的依赖注入器获得的Service(称为auth),问题是控制台告诉我以下内容:
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:
例外:TypeError:this.auth未定义
EXCEPTION: TypeError: this.auth is undefined
constructor(private auth: AuthService){
setInterval(function(){ this.auth.refreshToken(); }, 1000 * 60 * 10);
}
setInterval提供的函数中的
推荐答案
this 在调用该类时未指向该类.
this in the function given to setInterval doesn't point to the class when it is called.
改为使用箭头功能.
constructor(private auth: AuthService){
setInterval(() => { this.auth.refreshToken(); }, 1000 * 60 * 10);
}
这篇关于Angular 2调用setInterval()未定义服务形式依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文