我正在使用socket.io实现小型聊天应用程序,很高兴它工作正常 . 但我担心的是,当我进行新的聊天时,我需要将其分配给字符串数组以在listview中显示 .
我只是将数组定义为 "messages: string[] = [];" 并在页面加载时推送样本字符串并且它工作正常 . 但是当我从套接字获取新消息时 this.socket.on('newmessage', function (data) 方法将触发并且可以读取新消息 . 所有事情都正常工作 .
但是当我将新字符串推入我的 "messages: string[] = [];" 数组时 . 我'm getting '无法读取属性'push' of undefined'错误 .
import { Component, OnInit} from '@angular/core';
import * as io from 'socket.io-client';
@Component({
selector: 'app-chatbox',
templateUrl: './chatbox.component.html',
styleUrls: ['./chatbox.component.css'],
})
export class ChatboxComponent implements OnInit {
socket;
messages: string[] = [];
constructor() { this.socket = io.connect('http://localhost:8000'); }
ngOnInit() {
this.initializeChatServer();
}
initializeChatServer() {
this.messages.push( 'test 55');//This line works
this.socket.on('newmessage', function (data) {
console.log('message -> ' + data.nick + '>' + data.msg);
this.messages.push(data.msg); //Cannot read property 'push' of undefined
});
}
}
3 回答
因为你错了
this
. 箭头功能将解决这个问题 . 将this.socket.on('newmessage', function (data) {
更改为this.socket.on('newmessage', (data) => {
我认为这是因为同步调用 . 我认为它不是标准的方式,但它在我改变之后起作用..