如何在我的服务中删除事件监听器?

时间:2018-10-10 08:06:56

标签: angular events broadcast

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

  }

0 个答案:

没有答案