anderlaini
anderlaini

Reputation: 1821

ionic 4 - How to wait for two observables to be subscribed before getting data

I'm accessing this route fine:

http://localhost:8100/questions/question?id=3

Now I'm in trouble on how to handle two subscribers at the same time.

The first subscriber loads the questions array from the external service.

The second one gets the desired Question object according to the route param.

app_data:AppData;
question:Question;

ngOnInit() {
  this.appService.app_data.subscribe((v) => { this.app_data = v; });

  this.route.queryParams.subscribe(p => {
    this.question = this.appService.app_data.questions.find(i => i.id === params.id);
  });
}

The problem is that when I open this route, it tries to filter the array which is still not loaded by the service.

ERROR TypeError: Cannot read properties of undefined (reading 'find')

Am I doing something wrong?

Upvotes: 0

Views: 146

Answers (1)

Yong Shun
Yong Shun

Reputation: 51125

Would suggest using combineLatest rxjs operator to combine multiple observables and take the last emitted value.

When any observable emits a value, emit the last emitted value from each.

import { combineLatest } from 'rxjs';

combineLatest([this.appService.app_data, this.route.queryParams]).subscribe(
  ([appData, param]) => {
    this.app_data = appData;
    this.question = appData.questions.find((i) => i.id === param.id);
  }
);

Demo @ StackBlitz


Bonus:

forkJoin aims to wait for all the Observables to be completed first then only emit their last emitted value for each observable. However route.params, route.queryParams observables will never be completed, thus forkJoin is not working in this scenario.

Upvotes: 1

Related Questions