Angular 2: event translation service

I am trying to create an event broadcast service.

Here is a basic concept that I would like to achieve:

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 method like this
                } 
             }
        );
   }
}

I know that I cannot call a component method from a service like this. I have to somehow observe and call it a component. I am not sure how to achieve this.

Thanks for any advice.


Decision

Thanks to AngularFrance , here is the solution for 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);
  }

}
+4
source share
2 answers

You must return the observable from BroadcastService(NB. A Subject- 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);
     }
}

Then subscribe to the returned observable from the component:

export class MyComponent {

  constructor(bcservice: BroadcastService) {
    // Subscribe here.
    bcservice.getEvents(event).subscribe(eventValue => {
      this.someMethod();
    });
  }

  someMethod() { }

}

. , , ( next()), .

+4

Source: https://habr.com/ru/post/1669920/


All Articles