2017-06-14 97 views
-1

我有一個使用setInterval聲明中的setInterval函數不更新

public getMoreMessages(route: string) { 
    this.http.get(this.url + route + "?page=" + MessageService.plus) 
      .subscribe(function(response) { 
    if (response.json.length === 0) { 
     MessageService.plus++; 
     this.extractAndUpdateMessageList(response); 
     return; 
    }; 
    }); 
} 

這裏的問題是,在function定義的一切都必須static,否則這將是undefined此方法。這就是爲什麼我宣稱plusstatic,但我無法聲明extractAndUpdateMessageList(響應:響應)也是static

有人可以幫我弄清楚如何正確寫入它,而不必聲明我的變量爲static

謝謝

+0

它在哪裏使用'setInterval'? –

回答

0

你的subscribe的回調函數內上下文(this)當您使用function() {}語法回調。使用arrow functions捕捉正確this

this.http.get(this.url + route + "?page=" + MessageService.plus) 
    .subscribe((response) => { // Notice arrow function here 
    if (response.json.length === 0) { 
     MessageService.plus++; 
     this.extractAndUpdateMessageList(response); 
     return; 
    }; 
    }); 

你不必做MessageService.plus爲靜態,你現在會得到與箭頭功能回調內部實例屬性。

+0

這實際上是我第一次嘗試,但我注意到它並沒有計算好像它不存在的條件,無論response.json是否執行內部代碼,我真的很困惑... – jiji

+0

@jiji聽起來像你的數據有問題。檢查'response.json'是否是一個數組,並且你的邏輯是正確的。 – Saravana

+0

我切換到你的技術'((response)=> {',當我做'console.log(response.json())'時,我總是得到'null'但是當我使用'function(response ){'它正確打印數組......我無法弄清楚它! – jiji

0

我想你只需要使用

let that = this; 

,並用「」在地方回調裏面。

+0

替換'function(response){'改變類的屬性不只是一個局部變量! – jiji