【问题标题】:Cannot read property 'messages' of undefined无法读取未定义的属性“消息”
【发布时间】:2017-03-08 19:22:40
【问题描述】:

从 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 - 因此视图会使用以前的消息进行更新,然后 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。

【问题讨论】:

    标签: node.js mongodb sockets angular


    【解决方案1】:

    不要使用function (),而是使用() =&gt;(箭头函数)让this....继续指向本地类实例

    tracks.forEach((item) => {
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-14
      • 2018-10-09
      • 2018-11-14
      • 1970-01-01
      • 2018-11-20
      • 2021-02-25
      • 2019-01-09
      相关资源
      最近更新 更多