为什么即使初始化为数组后,Typescript仍然无法读取推式方法? (ANGULAR2)
问题描述:
我试图创建一个使用pubnub和Angular2的聊天应用程序,但我坚持在这一部分。为什么即使初始化为数组后,Typescript仍然无法读取推式方法? (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
}
});
}
请帮帮忙,这似乎出于某种原因我不能访问该部分消息数组,大概是为什么它不能检测push方法。
答
使用箭头功能应该能够解决您的问题
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
}
查看关于箭头的功能在这里
+0
感谢:D它的工作 –
我不知道上面的addListener()会发生什么情况的详细信息,但在这一行你会得到错误,这个消息不是你期望的那样。 – Cristina