Muffadal
Muffadal

Reputation: 111

using $on and $broadcast with angular 2

Currently with angularjs 1, I am using the $on and $broadcast event mechanisms, which are available as part of $rootscope and $scope, to handle communication between a controller and a service. However, with the introduction of AngularJS 2, $rootscope and $scope will become unavailable. So, if I want to make my application AngularJS 2-compliant, then what should I do to get the same effect as $on and $broadcast.

Upvotes: 11

Views: 11014

Answers (3)

kushal
kushal

Reputation: 181

AngularJs inbuilt does not provide Broadcast and Emit, you can implement with custom code like Plnkr

Upvotes: 0

Thierry Templier
Thierry Templier

Reputation: 202156

You could use a shared service containing a property of type Observable. Here is a sample 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 can notice that you need to share the observable because it's cold by default.

An important thing consists in defining your service when bootstrapping your application to be able to use the same instance within the whole application:

bootstrap(AppComponet, [ SharedService ]);

Here is the corresponding plunkr: https://plnkr.co/edit/bpIVxRrWggLVrS9BdQ6w?p=preview.

See this question for more details:

Upvotes: 11

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657248

There is no such thing in Angular2. Custom shared services are used for this. See also Global Events in Angular 2

Upvotes: 0

Related Questions