Home > Mobile >  Combine forkJoin and activatedRoute
Combine forkJoin and activatedRoute

Time:11-30

I have the following observable:

formData$ = forkJoin([
    this.httpService.getProgramsLevelsList(),
    this.httpService.getProgramsTypesList(),
    this.httpService.getQuestionnaireReasonsList()
]).pipe( tap((res: any) => { console.log(res)     }),     );

And this produces an object with 3 inner arrays. ie

{
    [arr1],
    [arr2],
    [arr3]
}

I also have another observable:

existingFormData$: Observable<UniversityApplicationsDetail> =
    this.activatedRoute.params.pipe(
        map(params => params['id']),
        filter(id => !!id),
        switchMap((id: string) => this.httpService.getUniversityApplicationsDetail(id))
);

And this observable grabs an id off the url (if it exists) and returns an object from the Back End.

Can I combine these 2 observables together so I get the following result:

{
    [arr1],
    [arr2],
    [arr3],
    {objApplication} //This might optionally be here
}

CodePudding user response:

When using forkJoin you need to make sure that every observable emits a value. You could change existingFormData$ to emit undefined when there is no id, instead of never emitting anything.

//                                                           VVVVVVVVV
existingFormData$: Observable<UniversityApplicationsDetail | undefined> =
  this.activatedRoute.params.pipe(
    map(params => params['id']),
    switchMap((id) => id 
      ? this.httpService.getUniversityApplicationsDetail(id)
      : of(undefined)));

You can add this to formData$:

formData$ = forkJoin([
    this.httpService.getProgramsLevelsList(),
    this.httpService.getProgramsTypesList(),
    this.httpService.getQuestionnaireReasonsList(),
    existingFormData$,
]).pipe( tap((res: any) => { console.log(res)     }),     );

... to get an Observable of a tuple, where the last element might be undefined or UniversityApplicationsDetail.

  • Related