dcp3450
dcp3450

Reputation: 11187

Angular observable doesn't get initial value

I have three components on my screen, one of which is a list pulled from a database. The two wait for the list to load. The user can switch between the other two components and the list doesn't need to reload.

I'm using a service to tell the two components the list is finished loading.

When the list finishes the currently viewed component will display. However, if the user switches the view after the list loads the new view is still waiting for the observable to trigger.

editor.service.ts:

...
private setBusReady = new Subject<boolean>();
...
getBusReady = this.setBusReady.asObservable();
...
busReady(values: boolean = false) {
  this.setBusReady.next(values);
}

list.component.ts (sets busReady to true once loaded)

...
this.editorService.busReady(true);
...

viewer.component.ts (subscribes and waits for list)

...
ngOnInit() {
  ...
    this.editorService.getBusReady
    .pipe(
      takeUntil(this.unsubscribe)
    )
    .subscribe(res => {
      if (res) {
        this.loading = !res;
      }
    });
  ...
}
...

The views with the subscribe have no issues when loading but do when they are switched. I think I need to switch to a hot observable but I'm not sure. I tried doing that with a ConnectableObservable but that cause other issues.

Upvotes: 0

Views: 1798

Answers (1)

Fateh Mohamed
Fateh Mohamed

Reputation: 21367

i think that you should use BehaviourSubject, because Subject doesn't hold the current value when you subscribe and it only trigger on .next (the moment when your data is loaded only ), on the other side BehaviourSubject can hold one previous value and all upcomming ones

Upvotes: 3

Related Questions