angular - 如何在我的服务中删除事件监听器?
问题描述
我是 Angular 的新手,我想知道如何在我的服务中删除事件监听器,以便它停止接收任何数据。我目前正在尝试交流,其中第 1 页使用广播频道向第 2 页发送消息。提前谢谢。`
export class Page2Component implements OnInit {
private xx : any;
public person = {} as Person;
constructor(public broadCastService : BroadcastService) {
}
ngOnInit() {
this.xx=this.broadCastService.events.subscribe((e) => {
this.person.age =e.age;
this.person.name = e.name;
});
console.log("onInit");
}
ngOnDestroy() {
//I tried adding here but it does not remove
this.broadCastService.channel.removeEventListener("message",this.ngOnDestroy)
this.xx.unsubscribe();
console.log("onDestroy");
}
}
<div class="column-6">
<h2>This is the PAGE 2</h2>
<p>Message will be display here from first.html</p>
Name: {{person?.name}}<br>
Age: {{person?.age}}<br>
<button (click)="ngOnDestroy()">unsubcribe</button><button (click)="ngOnInit()">subcribe</button>
</div>
`
export class BroadcastService {
public events: Observable<any>;
private channel = new BroadcastChannel('test_channel');
constructor() {
this.events = new Observable ((observer) =>{
this.channel.addEventListener ('message', (ev) =>{
observer.next(ev.data);
})
this.channel.onmessageerror = ev => {
observer.error(ev);
}
//I TRIED ADDING removeEventListener here but doesnt work
});
}
public addPerson(person : any) {
this.channel.postMessage(person);
}
}
解决方案
推荐阅读
- html - Firefox 与 Chromium 上边框/边框半径的不同结果
- reactjs - 我们如何让 pixi-viewport 跟随 pixi-react 组件?
- maven - Flink:jar文件中找不到程序的入口点类
- html - 如何将文本旋转 90 度并删除原始边距
- python - 如何在 python 中以更有效的方式编写以下代码?
- javascript - 我无法将我的数组从我的控制器获取到 codeigniter 中的 ajax
- html - 反转css以将其分成两个部分
- python - 更改值在我的列表中的位置
- python - discord.py Bot 不响应 DM 中的输入
- asp.net-mvc - Kendo MultiSelect 未在 Kendo Grid 弹出窗口中呈现