yeaaaahhhh..hamf hamf
yeaaaahhhh..hamf hamf

Reputation: 788

Angular (version 8) - Subscribe not firing

I'm trying to establish communication between components by using observables and Subject.

This is my service.

CommonService

  private style = new Subject<string>();

  getStyle(): Observable<any> {
    return this.style.asObservable();
  }

  updateStyleArray(styleToApply) {
    this.style.next(styleToApply);
  }

The component in which i try to subscribe with the getStyle() method, has the following code inside the constructor.

BottomBar

    this.commonService.getStyle().subscribe(style => {
      console.log('I am firing in order not to be fired!!!');
    });

The component in which i call the next() method has the following code.

Sidebar

 this.commonService.updateStyleArray('This is the name of a style');

I have simplified the code to a bare minimum but it still doesn't fire the subcribe() function.

----> Stackblitz

Solution and NOTE

The above technique works like a charm in order to establish communication between components. The error was caused because app-bottom-bar was implemented with an ngIf* and the constructor was not called*, therefore the subscribe function was not called.

*<app-bottom-bar *ngIf="isBottomBarVisible"></app-bottom-bar> .

Upvotes: 1

Views: 1129

Answers (3)

Andrew Allen
Andrew Allen

Reputation: 8052

The BottomBarComponent constructor is not called. Hence you haven't actually subscribed.

Fix - stick this in app.component.html

<app-bottom-bar></app-bottom-bar>

Upvotes: 1

Max K
Max K

Reputation: 1121

Subject will not replay old values for new subscribers. Therefore, if you called updateStyleArray() before your subscription happens, it will not fire until a new call to updateStyleArray() will be made.

To solve this you could replace your Subject with a ReplaySubject and set the buffer size to 1:

  private style = new ReplaySubject<string>(1);

Now your style observable will buffer the last value and also emit this value if you subscribe after style.next() was called.

Upvotes: 0

Rahul Tokase
Rahul Tokase

Reputation: 1218

Can you change

private style = new BehaviorSubject <string>();

It could happen that bottombar is render before the sidebar hence causing the subscription to be lost. BehaviorSubject will make the last subscription available to all the component.

Thanks

Upvotes: 0

Related Questions