Mergemap Observable which depends from previous gets ignored,with HTTPClient calls, Angular

307 Views Asked by At

I want to execute three functions from a service as Observables to pass data until the last one. A component subscribes to them using a MergeMap method but the last function is not even accessed.

The service works like this:

public GetFirstUrl(firstname: string): Observable<FirstValue[]>{
   const url = 'https://graph.microsoft.com/v1.0/groups/'+firstname+'/events';
   return this.http.get<First>(url).pipe(map(.........)) (etc.)
}

public GetSecondUrl(secondname: string): Observable<SecondValue[]>{
   const url = 'https://graph.microsoft.com/v1.0/groups/'+secondname+'/events';
   return this.http.get<Second>(url).pipe(map(.........)) (etc.)
}

//this third method is never accessed
public GetThirdUrl(thirdname: string): Observable<ThirdValue[]>{ 
   const url = 'https://graph.microsoft.com/v1.0/groups/'+thirdname+'/events';
   return this.http.get<Third>(url).pipe(map(.........)) (etc.)
}

and the component that tries to access these links works like this:

ngOnInit(): void {
    this.nameService.GetFirstUrl('TestName1').pipe(
          mergeMap((res1) => this.nameService.GetSecondUrl(res1[0].secondname)),
          mergeMap((res2) => this.nameService.GetThirdUrl(res2[0].thirdname))
        ).subscribe((res3) => {
          const FinalValue = res3; // this line is ignored
        });
}

Why can't this approach work? Is it because of asynchronous procedure passing data one after another in a weird manner?

(Debugging error from last url is this 'ERROR TypeError: Cannot read property '0' of undefined' even though the function is never accessed when i try to place a breakpoint there (saw it on chrome console))

(edit: used concatmap, still same issue. res1[0].secondname is undefined so it leads to an undefined res2[0].thirdname)

1

There are 1 best solutions below

0
On

Ended up working only with concatMap as an approach and I found a typo in my model which should be referenced exactly as the http call "value" in Graph. Solved!

ngOnInit(): void {
    this.nameService.GetFirstUrl('TestName1').pipe(
          concatMap((res1) => this.nameService.GetSecondUrl(res1[0].secondname)),
          concatMap((res2) => this.nameService.GetThirdUrl(res2[0].thirdname))
        ).subscribe((res3) => {
          const FinalValue = res3; // this line is ignored
        });
}
export interface PlannerPlans{
    value: PlannerPlansValue[]; // this should be named exactly value, not val or anything different
}

Wasn't matching before with this

{
"value": [
        {
            "id": "ExampleIdFNBNEGAIBGNAGVKGOE"
        }
   ]
}