订阅可观察并获取特定类型的事件

时间:2019-05-16 18:07:56

标签: angular typescript rxjs angular6 angular7

我有以下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的事件做出反应...

这可能吗?我该怎么办?

1 个答案:

答案 0 :(得分: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();
   }
}