Issue
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?
Solution
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.
Answered By - sebaferreras
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.