Using $ on and $ broadcast with angular 2

Currently, using angularjs 1, I use event mechanisms $onand $broadcast, which are available as part of $rootscopeand $scope, to handle communication between the controller and the service. However, with the introduction of AngularJS 2, $rootscopeboth $scopewill become unavailable. So, if I want to make the app AngularJS 2-compatible, what must I do to get the same effect as $onand $broadcast.

+4
source share
3 answers

You can use a generic service containing a type property Observable. Here is an example implementation:

export class SharedService {
  observable: Observable;
  observer: Observer;

  constructor() {
    this.observable = Observable.create((observer:Observer) => {
      this.observer = observer;
    }).share();
  }

  broadcast(event) {
    this.observer.next(event);
  }

  on(eventName, callback) {
    this.observable.filter((event) => {
      return event.name === eventName;
    }).subscribe(callback);
  }
}

You may notice that you need to share what is observable because it is cold by default.

, :

bootstrap(AppComponet, [ SharedService ]);

plunkr: https://plnkr.co/edit/bpIVxRrWggLVrS9BdQ6w?p=preview.

. :

+5

Angular2 . . . Angular 2

0

AngularJs , , Plnkr

0

All Articles