how to destroy/unsubscribe broadcast message event in angular2

1k views Asked by At

I am developing application in angular2, here I have used message broadcast for updating data from one component to other.

here is code, message_event.ts

import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Broadcaster} from './broadcaster';

@Injectable()
export class MessageEvent {
  constructor(private broadcaster: Broadcaster) {}

  fire(data: string): void {
    this.broadcaster.broadcast(MessageEvent, data);
  }

  on(): Observable<string> {
    return this.broadcaster.on<string>(MessageEvent);
  }
}

broadcaster.ts

import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';

interface BroadcastEvent {
  key: any;
  data?: any;
}

export class Broadcaster {
  private _eventBus: Subject<BroadcastEvent>;

  constructor() {
    this._eventBus = new Subject<BroadcastEvent>();
  }

  broadcast(key: any, data?: any) {
    this._eventBus.next({key, data});
  }

  on<T>(key: any): Observable<T> {
    return this._eventBus.asObservable()
      .filter(event => event.key === key)
      .map(event => <T>event.data);
  }
}

I have registered/subscribed in this event in one of component.

ngOnInit() {
    // this.registerStringBroadcast();
    this.registerTypeBroadcast();

    this.loadId();
  }

  registerTypeBroadcast() {
    this.message_event.on().subscribe(message => {
      // alert("true");
      this.isUserLogin = true;
      this.loadId();
    })

Here i need to check event already register or not. Or Is there any way to destroy/unsubscribe this message event.

Please help me for above.

Thanks in advance.

1

There are 1 answers

0
Marco Rosas On

You can call the unsubscribe() function of a subscription object.

You will need to assign the subscription to an object, and then invoke the unsubscribe when you don't need it anymore.

example:

var subscription$ = this.someservice.subscribe(params);

subscription$.unsubscribe();