[英]Angular BroadcastChannel: Send Data between Two Browser Tabs, Property does not exist on type 'BroadcastChannel'
How do I use Broadcast channel with Angular Typescript?如何将广播频道与 Angular Typescript 一起使用? We are sending data between two browser windows, (this is per UX design).
我们在两个浏览器 windows 之间发送数据(这是每个 UX 设计)。 Getting error below.
下面出现错误。 Why doesn't the property exist?
为什么财产不存在?
Trying to receive data in second component continuously, anytime something is sent.尝试在第二个组件中连续接收数据,无论何时发送某些东西。
Reading this resource: https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API阅读此资源: https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API
Sender Component is doing following:发件人组件正在执行以下操作:
ngOnInit() {
const bc = new BroadcastChannel('test_channel');
bc.postMessage('GetData');
Receiving Component:接收组件:
ngOnInit() {
const bc = new BroadcastChannel('test_channel');
bc.onmessage = function (ev) {
if (ev.data == "GetData") {
this.productName = "test;
}
}
}
Error: Property 'productName ' does not exist on type 'BroadcastChannel'.
错误:“BroadcastChannel”类型上不存在属性“productName”。
The issue you're having is the value of this
.您遇到的问题是
this
的值。 In the function which you have assigned to bc.onmessage
, the value of this is the function, not the surrounding class/instance.在您分配给
bc.onmessage
的 function 中,此值是 function,而不是周围的类/实例。 The easiest way to have a function whilst having the value of this
as the instance is to use an arrow function.拥有 function 同时将其
this
作为实例的最简单方法是使用箭头 function。 ie IE
ngOnInit() {
const bc = new BroadcastChannel('test_channel');
bc.onmessage = (ev) => {
if (ev.data == "GetData") {
this.productName = "test;
}
}
That should fix the error.那应该可以解决错误。
However, I would like to point out that whilst the above would work, I wouldn't consider the BroadcastChannel API as an appropriate way of passing data between components.但是,我想指出,虽然上述方法可行,但我不会将 BroadcastChannel API 视为在组件之间传递数据的适当方式。 There are quite a few better ways of doing it:
有很多更好的方法来做到这一点:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.