问题
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