首页 > 解决方案 > 如何在我的服务中删除事件监听器?

问题描述

我是 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); 
  }

  }

标签: angulareventsbroadcast

解决方案


推荐阅读