[英]Angular 2 : cannot read property 'push' of undefined
在我的Angular 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:無法讀取未定義的屬性“ push”(…)
有什么建議嗎?
更改
notification : Array<any>;
至
notification : Array<any> = [];
我遇到了相同的推字符串消息問題,並且以下代碼已解決了我的問題。
messages: Array<string> = [];
add(message: string): void {
this.messages.push(message);
}
我遇到了同樣的問題,然后發現我忘記初始化服務方法本身,並且將其類型設置為any。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.