首页 > 解决方案 > 在 Angular 4 中订阅 Web 套接字后无法使用来自套接字的消息更新 UI 元素

问题描述

我正在编写 Angular 4 编码。我有一个 Web 套接字,我可以使用 console.log() 记录来自 Web 套接字的消息,但是当我使用该消息更新变量时,同样不会反映在 UI 上。请在下面找到代码。

constructor(private zone: NgZone, private cdRef: ChangeDetectorRef, private DataService1: DataService, private calcSevice: PostService, private datepipe: DatePipe, private elementRef: ElementRef) {
    this.ws = new SockJS(this.serverUrl);
    this.stompClient = Stomp.over(this.ws);
    let that = this;
    this.stompClient.connect({}, function (frame) {
      that.stompClient.subscribe("/updates/public", (message) => {
        //this.zone.run(() => {
        alert("got message");
        this.refreshErrorMessage = message.body;
        console.log("Message from socket is" + this.refreshErrorMessage);
      });

      //});
    });
}

我认为这是 zone 的问题,所以我将上面注释的 ngzone 代码放在两行中,但随后它给了我无法读取未定义错误的属性“运行”。请帮忙

标签: angularasynchronouswebsocketsubscribengzone

解决方案


推荐阅读