[Fixed] Ionic Events replace with Angular Observables

Issue

I understand Ionic events will be deprecated in next version. Currently I use events to executes functions in my parent page from sub components. Here is an example:

In my main page it subscribes to the event to refresh:

constructor(){
  this.eventFormRefresh = (obj) => {
    this.fetch(obj.isReset);
  };
  this.events.subscribe('form:refresh', this.eventFormRefresh);
}

ngOnDestroy(): void {
  this.events.unsubscribe('form:refresh', this.eventFormRefresh);
}

In a subcomponent I activate the refresh by publishing the ‘form:refresh’ event as so:

this.events.publish('form:refresh');

How would I do the above using angular observables?

Solution

you can use rxjs Subject for that so first create a common service eg.

@Injectable()
export class EventService{
  private formRefreshAnnouncedSource = new Subject();
  formRefreshSource$ = this.formRefreshAnnouncedSource.asObservable();

  publishFormRefresh(){
    this.formRefreshAnnouncedSource.next()
  }

}

then publish like

this.eventService.publishFormRefresh();

and subscribe in some componenet

this.subscription = this.eventService.formRefreshSource$.subscribe(data => {
  //do something here
});

and cancel subscription on ngOnDestroy

this.subscription.unsubscribe()

Leave a Reply

(*) Required, Your email will not be published