我正在使用 socket.io 实现小型聊天应用程序,很高兴它工作正常。但我担心的是,当我收到新聊天时,我需要将其分配给字符串数组以在列表视图中显示。
我只是将数组定义为“消息:字符串 [] = [];” 并在页面加载时推送示例字符串,它工作正常。但是当我从套接字this.socket.on('newmessage', function (data)方法将触发并可以读取新消息时,所有的东西都正常工作。
但是当我将新字符串推入我的“消息:字符串[] = [];”时 大批。我收到“无法读取未定义的属性“推送”错误。
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
});
}
}
我认为这是因为同步调用。我认为这不是标准方式,但在我这样更改后它起作用了..
initializeChatServer() {
this.messages.push( 'test 55');
var self = this;//assgin this to var variable
this.socket.on('newmessage', data => {
console.log('message -> ' + data.nick + '>' + data.msg);
self.messages.push(data.msg);
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句