L.querter
L.querter

Reputation: 2522

Angular 2 | Subscriping to Observables

I'm trying to get 2 components to talk to each other by using a middelman (Service).

I have a photoshop like app, and i want a component(a window with a button) to add a layer in my 'imageView'.

they are both nested in other views so i can not use '@Output'.

Button triggers:

  addLayer() {
     this._broadcastService.addLayer(0);
  }

Receiving component:

  constructor(private _broadcastService:BroadcastService) { }

  ngOnInit() {
      this.subscription = this._broadcastService.layer$.subscribe(
      data => this.test(data))
  }

Broadcast service:

  private _layerSubject = new BehaviorSubject<number>(0);

  layer$ = this._layerSubject.asObservable();

  addLayer(data: number) {
      this._layerSubject.next(data);
  }

The receiving component is not getting anything. He does not trigger, only once on startup, I want to trigger something every time i press the add layer button.

thank you !

Upvotes: 4

Views: 110

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658067

You need to provide BroadcastService once on a common parent component like

   @Component({
     selector: '...',
     provide: [BroadcastService],
   })
   class AppComponent {}

To share the same instance with the whole application provide it at the root component which is the common parent of all your components and directives in your Angular2 application. (alternatively you can provide it at bootstrap(AppComponent, [BroadcastService]))

If you provide it at other components, this component and its children will get a different instance of the service.

Upvotes: 2

Related Questions