所以在下面的代码中,我在从websocket接收到一个对象之后推送它。在此之后,我想调用setInterval并每隔60秒向messages数组中对象的minutesAgo属性添加一分钟。
不幸的是,ERROR TypeError: Cannot read property 'forEach' of undefined
函数中出现错误getMinutesAgo()
。我之前将对象推送到messages数组中,所以我不明白为什么this.messages
未定义。有人知道为什么吗?
export class MovieChatComponent implements OnInit{
fullName;
title = 'Websocket Demo';
url;
ws;
messages = [];
movieChatElem;
constructor(private movieChatService: MovieChatService){
}
ngOnInit(){
this.fullName = localStorage.getItem('fullName');
this.url = 'ws://localhost:3185';
this.movieChatService.createObservableSocket(this.url)
.subscribe(obj => {
console.log(obj);
this.messages.push(obj);
console.log(this.messages);
this.movieChatElem.scrollTop = this.movieChatElem.scrollHeight - this.movieChatElem.clientHeight;
this.startTimeCalculations()
},
err => console.log(err),
() => console.log('The observable stream, is complete'));
}
startTimeCalculations(){
setInterval(this.getMinutesAgo,60000);
}
getMinutesAgo (){
console.log('entered');
console.log(this.messages);
this.messages.forEach(function (msg) {
msg.minutesAgo++;
console.log('done');
console.log(msg.minutesAgo);
})
}
}