Searching alternative for events in ionic 5 [closed]

大兔子大兔子 提交于 2020-12-12 12:01:06

问题


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

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