无法读取未定义的属性'messages'



当从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();
    }
}

This is my 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并通过套接字。IO发送到所有连接的套接字。

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

在页面加载时,我想从文档存储中检索这些消息,并将它们推送到this.messages上——这样视图就会用以前的消息更新,然后是套接字。IO应该接管新消息,将它们添加到数组中。

因为这是一个初始调用,一旦加载,我不使用socket。我通过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。

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

tracks.forEach((item) => {
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

最新更新