2016-03-06 63 views
15

我想通過使用setInterval()每10分鐘調用一個函數,並且在此函數中我想使用從Dependency獲得的Service(稱爲auth)角2的注射器,問題是,控制檯告訴我下面的:Angular 2 call setInterval()undefined服務形式依賴注入

EXCEPTION: TypeError: this.auth is undefined

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

'的setInterval(()=> this.auth.refreshToken(),1000 * 60 * 10);' –

回答

38

在給setInterval的時候它被稱爲不指向類的功能。

改爲使用箭頭功能。

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

優秀交關於這一主題這裏:http://www.2ality.com/2012/04/arrow-functions.html –

2

此問題的full discussion可以爲setInterval()方法的文檔中找到,標題「此」問題。大約在頁面的一半。

jist是它是「this」變量發生變化的結果。傳遞給setInterval()函數的函數從類上下文中提取並放入setInterval()(窗口)的上下文中。所以,它是不​​確定的。

這個問題有幾種解決方案。上述toskv提出的方法是一種相當普遍的方法。 另一種解決方案是使用bind()方法。

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

參考資料來自this question,由Pointy回答。

bind() method的文檔。

關於javascript scope的好文章,它仍然可以在打字稿中回來咬你。

0

解決這個問題有一個小技巧。希望這可以幫助。

首先做

const this1 = this; 

然後

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