angular - 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>
收到的消息始终为空,但在控制台中我可以看到新消息。
解决方案
你失去了上下文this
。尝试使用箭头功能以保留this
:
like this
\/
fx.onmessage = evt => {
this.newMessage = evt.data;
console.log(this.newMessage);
}
推荐阅读
- css - 如何在 CSS 中进行设计,如下图所示
- python - 如何将某些多维数组的索引“分组”为低维数组(低阶张量)?
- css - 具有相同 unicode 的字体很棒
- android - 如何在点击和滚动时打开/关闭布局?
- rx-swift - 抛出错误替代 catchErrorJustReturn 的 RxSwift Observable
- sql - 如何在 SQL 中连接 4 个不通过 1 个 ID 相互连接的表?
- php - PHP cURL:使用 -F 选项发出 cURL 请求
- c - 动态内存分配中填充的重要性
- javascript - 关于mongoldb中用户数据建模的探讨
- python - 将numpy数组中的线性序列转换为几何级数序列