Home > Enterprise >  ionic 4 - how to wait for two subscribes before getting data
ionic 4 - how to wait for two subscribes before getting data

Time:12-27

I'm acessing 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 external service.

The second one gets the desired Question object according to 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?

CodePudding user response:

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 the Observable to complete first then followed by the next one, however route.params, route.queryParams observables will never be completed, thus forkJoin is not working in this scenario.

  • Related