Angular 2:事件广播服务

时间:2017-02-16 11:13:53

标签: angular typescript

我正在尝试创建事件广播服务。

这是我想要实现的基本概念:

export enum Event {
   EVENT_A,
   EVENT_B, ...
}


@Injectable()
export class BroadcastService {

     private broadcastSubject: Subject<Event> = new Subject<Event>();

     public next(event: Event): void {
         return this.broadcastSubject.next(event);
     }

     public subscribe(event: Event, componentCall: Function): void {
         this.broadcastSubject.subscribe(
             eventValue => {
                if(event === eventValue) {
                  componentCall(); // not possible to call component's method like this
                } 
             }
        );
   }
}

我知道我不能从这样的服务中调用组件的方法。我必须以某种方式返回observable并从组件中调用它。我不知道如何实现这一目标。

感谢您的任何建议。

感谢AngularFrance,这是BroadcastService的解决方案:

@Injectable()
export class BroadcastService {

  private broadcastSubject: BehaviorSubject<Event> = new BehaviorSubject<Event>(0);

  public next(event: Event): void {
     return this.broadcastSubject.next(event);
  }

  public subject(event: Event): Observable<Event> {
     return this.broadcastSubject.asObservable().filter(e => e === event);
  }

}

2 个答案:

答案 0 :(得分:4)

您应该从ProducerInterceptor返回可观察量(注意:A BroadcastServiceSubject):

Observable

然后从组件中订阅返回的observable:

@Injectable()
export class BroadcastService {

     private event: Subject<Event> = new Subject<Event>();

     public next(event: Event): void {
       return this.event.next(event);
     }

     public getEvents(event: Event): Observable<Event> {
       // DO NOT SUBSCRIBE HERE. Return the observable.
       return this.event.asObservable()
         // Only keep events matching the given `event` param
         .filter(e => e == event);
     }
}

注意:如果您只想在流中使用特定类型的事件,那么在 将其添加到流中之前过滤掉不需要的事件(在export class MyComponent { constructor(bcservice: BroadcastService) { // Subscribe here. bcservice.getEvents(event).subscribe(eventValue => { this.someMethod(); }); } someMethod() { } } 中)可能更为理想方法)而不是返回流时。

答案 1 :(得分:0)