Ionic Events replace with Angular Observables

元气小坏坏 提交于 2020-02-21 06:04:33

问题


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?


回答1:


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()



回答2:


You can create a service with a BehaviorSubject and you can pass data and subscribe to it wherever you want. In your case pass in the child and subscribe in the parent component.



来源:https://stackoverflow.com/questions/58265379/ionic-events-replace-with-angular-observables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!