2016-11-17 40 views
3

財產「推」在我的角2應用程序,我有一個函數:角2:不能讀取的不確定

notification : Array<any>; 
...... 
...... 
getNotification() { 
    return setTimeout(() => { 
     this.AppbankService.notify(this.user.NameId) 
    .subscribe(
     (response) => { 
      if (response.status === 200) { 
      this.notifications.push(response.json()); 
      console.log(typeof(this.notifications)); 
       } 
      this.getNotification(); 
     } 
    ) 
    },5000)} 

在這個函數中,我得到通知,從服務器每5秒,並試圖將它們推到一個數組,但有一個:錯誤app.module.ts:104錯誤:TypeError:無法讀取屬性'推'的undefined(...)

任何建議嗎?

回答

8

變化

notification : Array<any>; 

notification : Array<any> = []; 
+0

thx它適合我,但你能告訴我爲什麼我必須這樣做嗎?類型不夠? –

+2

不,類型只指定可以在此屬性中存儲哪種類型的值,但它不具有值。用'= []'我們用一個有'.push()'方法的空數組初始化它。 –

+0

適合我..大 –

0

我不得不推串消息的同樣的問題,我的問題已經通過下面的代碼解決。

messages: Array<string> = []; 
    add(message: string): void { 
    this.messages.push(message); 
}