问题
Ionic 4 Components:
import {Events} from '@ionic/angular';
constructor(private auth: AuthService, private events: Events) {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
// Refresh token failed, logout user
this.events.publish('user:logout', 'La sesión ha expirado');
}
In Ionic 5 events are removed... How i need to chnage w.t.t ionic5 ..Pls let me know
EDIT ::
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({providedIn: 'root'})
export class EventService{
private formRefreshAnnouncedSource = new Subject();
formRefreshSource$ = this.formRefreshAnnouncedSource.asObservable();
publishFormRefresh(){
this.formRefreshAnnouncedSource.next()
}
}
How to add parameter this event service?
回答1:
You could build your own "events service" by using a subject behind the scenes:
// app-events.enum.ts
export enum AppEvent {
UserLogout = 'UserLogout',
// ...
}
// app-events.service.ts
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { AppEvent } from '../enums/app-event.enum';
interface EventDetails {
event: AppEvent;
payload?: unknown;
}
@Injectable({ providedIn: 'root' })
export class AppEventsService {
private eventsDispatcher = new Subject<EventDetails>();
public dispatch(event: AppEvent, payload?: unknown): void {
this.eventsDispatcher.next({ event, payload });
}
public onEvent(event: AppEvent): Observable<unknown> {
return this.eventsDispatcher.asObservable().pipe(
filter((eventDetails) => eventDetails.event === event),
map((eventDetails) => eventDetails.payload),
);
}
}
And then you can use it like this:
// dispatch
this.appEventsService.dispatch(AppEvent.UserLogout, 'La sesión ha expirado');
// listen to events
this.appEventsService
.onEvent(AppEvent.UserLogout)
.subscribe((message: string) => {
console.log(message);
});
I'm sure this could be improved if you need better support for types in the payload but it should be more than enough to replace Ionic Events as it used to work Ionic 3.
回答2:
First give the Subject a type, then pass a parameter(s) when you call next(), like so:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({providedIn: 'root'})
export class EventService{
private formRefreshAnnouncedSource = new Subject<string>();
formRefreshSource$ = this.formRefreshAnnouncedSource.asObservable();
publishFormRefresh(eventName: string){
this.formRefreshAnnouncedSource.next(eventName)
}
}
来源:https://stackoverflow.com/questions/64904870/searching-alternative-for-events-in-ionic-5