无法读取未定义的属性“消息”

时间:2016-10-26 12:17:02

标签: 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通过快速应用程序将消息存储在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。

1 个答案:

答案 0 :(得分:0)

不要使用function ()使用() =>(箭头函数)来this....继续指向本地类实例

tracks.forEach((item) => {

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