为什么在初始化数组后 Typescript 仍然无法读取 push 方法? (角度 2)

Why does Typescript still cant read push method even after initializing as array ? (ANGULAR2)

我正在尝试使用 pubnub 和 Angular2 创建一个聊天应用程序,但我卡在了这一部分。

import { Injectable } from '@angular/core';
import { PubNubAngular } from 'pubnub-angular2';

@Injectable()
export class ChatService {
  public uuid: string;
  public message: string;
  public messages = [];  <------------------- Already initialized
  public channel: string[];

  constructor(private pubnub:PubNubAngular) {

    //  .......  ///

    this.pubnub.addListener({
      message: function (m) {
        let msg: object = {
          origin: m.channel,
          timetoken: m.timetoken,
          content: m.message,
          sender: m.sender
        }
        this.messages.push(msg); <-------- PRODUCES A "CANNOT READ PROPERTY 
                                           'PUSH' OF TYPE UNDEFINED IN [NULL]" ERROR
      }
    });
  }

请帮忙,似乎出于某种原因我无法访问那部分的消息数组,可能是为什么它无法检测到推送方法。

使用箭头函数应该可以解决您的问题

message: (m) => {
  let msg: object = {
    origin: m.channel,
    timetoken: m.timetoken,
    content: m.message,
    sender: m.sender
  }
  this.messages.push(msg); <-------- now this is your component instance
}

在此处查看有关箭头函数的更多信息