我正在使用socket。我的angular7应用程序中的Io-client,用于监听来自节点服务器的事件。在活动中,我想在页面上显示一些数据。但监听事件的数据并没有更新。下面是我的代码
import { Component, OnInit } from '@angular/core';
import * as io from "socket.io-client";
@Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.css']
})
export class ChatComponent implements OnInit {
socket = io("http://localhost:3002");
constructor() { }
test:string;
ngOnInit() {
this.socket.on("adminrecivedMsg", function (data) {
this.test= "hello";
})
}
}
chat.component.html
{{测试}}
使用箭头函数,这个组件的关键字引用随着函数关键字而丢失。
ngOnInit() {
this.socket.on("adminrecivedMsg", (data)=> {
this.test= "hello";
})
}