Node.js 无法读取属性';信息';未定义的
从http服务返回并尝试将响应推送到阵列时,我遇到以下错误:Node.js 无法读取属性';信息';未定义的,node.js,mongodb,sockets,angular,Node.js,Mongodb,Sockets,Angular,从http服务返回并尝试将响应推送到阵列时,我遇到以下错误: Cannot read property 'messages' of undefined 这是我的chat.component.ts文件: import { Component, OnInit, OnDestroy } from '@angular/core'; import { ChatService } from './chat.service'; @Component({ selector: 'chat-compon
Cannot read property 'messages' of undefined
这是我的chat.component.ts文件:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ChatService } from './chat.service';
@Component({
selector: 'chat-component',
template: `
<div *ngIf="messages">
<div *ngFor="let message of messages">
{{message.text}}
</div>
</div>
<input [(ngModel)]="message" /><button (click)="sendMessage()">Send</button>
`,
providers: [ChatService]
})
export class ChatComponent implements OnInit, OnDestroy {
messages = [];
connection;
message;
loading;
constructor(private chatService: ChatService) { }
sendMessage() {
this.chatService.sendMessage(this.message);
this.message = '';
}
ngOnInit() {
this.chatService.initPlaylist().subscribe(tracks => {
tracks.forEach(function(item) {
this.messages.push({
message: item.trackID,
type: "new-message"
});
});
})
this.connection = this.chatService.getMessages().subscribe(message => {
this.messages.push(message);
})
}
ngOnDestroy() {
this.connection.unsubscribe();
}
}
我目前在前端有一个表单,用户可以在表单中添加消息,然后将消息推送到this.messages
,并通过socket.io发送到所有连接的套接字
我现在做的是通过使用mongoose的express应用程序将消息存储在mongodb中
在页面加载时,我希望从文档存储中检索这些消息,并将它们推送到this.messages
-这样视图将用以前的消息更新,然后socket.io将接管新消息,并将它们添加到数组中
由于这是一个初始调用,一旦加载,我不会使用socket.io获取这些,而是通过express设置api路由,返回json,如下所示:
[
{
"_id": "58109b3e868f7a1dc8346105",
"trackID": "This is my message...",
"__v": 0,
"status": 0,
"meta": {
"played": null,
"requested": "2016-10-26T12:02:06.979Z"
}
}
]
但是,当我在chat.component.ts
中找到这段代码时,所有内容都出现了前面提到的错误
this.chatService.initPlaylist().subscribe(tracks => {
tracks.forEach(function(item) {
this.messages.push({
message: item.trackID,
type: "new-message"
});
});
})
我使用Angular 2、Socket.io、ExpressJS和MongoDB。不要使用函数()
而是使用()=>(箭头函数)来表示这个….
以保持指向本地类实例
tracks.forEach((item) => {
tracks.forEach((item) => {