【问题标题】:Subscribe Observable and get Events of specific type订阅 Observable 并获取特定类型的事件
【发布时间】:2019-10-04 01:42:43
【问题描述】:

我有以下 Angular 服务:

export class EventService {

  private subject = new Subject<Event>();

  send(code: EventCode, data?: any) {
    this.subject.next(event);
  }

  clear() {
    this.subject.next();
  }

  get(): Observable<Event> {
    return this.subject.asObservable();
  }

}

Event 和 EventCode 在哪里:

export class Event {
  code: EventCode;
  data: any;
  constructor(code: EventCode, data?: any) {
    this.code = code;
    this.data = data;
  } 
} 

export enum EventCode {
  Created,
  Deleted,
  Updated
}

那我使用如下:

this.eventService.get().subscribe((event: Event) => { 
  // Do something 
});

我希望能够仅订阅具有特定 EventCode 的事件。

或者可能只对带有特定EventCode 的事件做出反应......

这可能吗?我该怎么做?

【问题讨论】:

  • 您可以使用过滤运算符。

标签: angular typescript rxjs angular6 angular7


【解决方案1】:

在我们开始之前,这是:

this.eventService.get().subscribe((event: Event) => { 
  // Do something 
});

当组件销毁时会泄漏内存,因为您没有取消订阅。改为这样做。

export class MyComponent implements OnInit, OnDestroy {
  // store subscrition
  private eventServiceSubscription: Subscription;

  ngOnInit() {
        this.eventServiceSubscription = this.eventService.get().subscribe((event: Event) => {
          // check event code
          if(event.code === 'someEventCode') {
            // process event
           }
         });
   }

   ngOnDestroy() {
     this.eventServiceSubscription.unsubscribe();
   }
}

【讨论】:

  • 是的,我已经取消订阅。为了简单起见,我省略了一些代码。是的,我还按照您的建议检查了 event.code。可能我不清楚:我正在尝试做类似this.eventService.get(EventCode.Delete).subscribe( 的事情。只是想知道这样的事情是否可能。
  • 我的意思是,EventService 将负责过滤本身...
  • 您想要一个向某些组件发出Foo 事件并向其他组件发出Bar 事件的单例服务?使用不同的主题,并重写您的send 方法以在正确的主题上调用next
猜你喜欢
  • 1970-01-01
  • 2019-08-05
  • 2017-12-03
  • 1970-01-01
  • 1970-01-01
  • 2018-06-27
  • 1970-01-01
  • 2017-08-05
  • 2021-02-09
相关资源
最近更新 更多