node.js - 无法读取未定义的属性 'messages'

标签 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-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();
    }
}

这是我的 chat.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Rx';
import * as io from 'socket.io-client';
@Injectable()
export class ChatService {
    private url = 'http://localhost:1337';
    private socket;
    constructor(private http: Http) {
    }
    sendMessage(message) {
        this.socket.emit('add-message', message);
    }
    initPlaylist() {
        return this.http.get(this.url + '/playlist')
            .map(this.extratData)
            .catch(this.handleError);
    }
    getMessages() {
        let observable = new Observable(observer => {
            this.socket = io(this.url);
            this.socket.on('message', (data) => {
                observer.next(data);
            });
            return () => {
                this.socket.disconnect();
            };
        })
        return observable;
    }
    private extratData(res: Response) {
        let body = res.json();
        return body || {};
    }
    private handleError(error: Response | any) {
        // In a real world app, we might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }
}

我目前在前端有一个表单,用户可以在其中添加一条消息,然后将其推送到 this.messages 并通过 socket.io 发送到所有连接的套接字。

我现在正在做的是使用 mongoose 通过 express 应用程序将消息存储在 mongodb 中。

在页面加载时,我想从文档存储中检索这些消息,并将它们推送到 this.messages - 这样 View 就会用以前的消息更新,然后 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。

最佳答案

不要使用 function () 而是使用 () => (箭头函数)让 this.... 保持指向到本地类实例

tracks.forEach((item) => {

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

关于node.js - 无法读取未定义的属性 'messages',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40262069/

相关文章:

javascript - 从nodejs服务器端进行ajax调用

javascript - 没有窗口对象存在 webpack nodejs

node.js - 在 Mongoose 中设置查找后转换 Hook 的最简单方法

javascript - 在 MongoDB 中使用 $lt 和 $gt 过滤日期值

node.js - 使用 Mongoose 在对象数组中查找 Schema

node.js - Socket.io 最佳编码实践

Node.js ExpressJS 模式匹配不等于

javascript - javascript中的Websockets,当页面刷新或导航到其他页面时连接终止

ios - 在没有 VoIP iOS 的情况下在后台保持 XMPP 套接字事件

传输字节数组时出现 Java OutOfMemory 问题