首页 > 解决方案 > EventSource 动态绑定变量

问题描述

我尝试更新并显示从变量更新到 EventSource 函数的消息:

ngOnInit(): void {
     const EventSource: any = window['EventSource'];
     const fx = new EventSource('/weather/update/');
     fx.onmessage = function (evt) {
          this.newMessage  = evt.data;
          console.log(this.newMessage);
     }
}

在模板中:

<p>{{newMessage}}</p>

收到的消息始终为空,但在控制台中我可以看到新消息。

标签: angular

解决方案


你失去了上下文this。尝试使用箭头功能以保留this

               like this     
                  \/
fx.onmessage = evt => {
   this.newMessage  = evt.data;
   console.log(this.newMessage);
}

推荐阅读