在离子5中寻找事件的替代方法 [英] Searching alternative for events in ionic 5

查看:98
本文介绍了在离子5中寻找事件的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

离子4成分:

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');
    
    }

在Ionic 5中事件已删除... 我需要如何更改ionic5 ..请让我知道

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?

推荐答案

您可以构建自己的事件服务"通过在幕后使用主题:

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);
    });

我敢肯定,如果您需要对有效负载中的类型提供更好的支持,那么可以改善这一点,但是它足以取代Ionic Events,因为它过去曾在Ionic 3上正常工作.

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.

这篇关于在离子5中寻找事件的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆