Multiple http calls angular 7

swingmicro

I am stuck with a situation where I have to get some data based on the parent Data

  1. I made a http get request to get all the components list and in the subscribe I have a forEach loop to iterate through each component.

  2. In the for loop for each component I making another http get call to get child for each Components.

  3. In the outer loop I have to push only the component name to new array and where as in the inner loop I have to push the child component names to the same array as a property 'children'.

Now the problem is outer loop is completing before inner one so the array is coming as below

[{name:'parentcomp1', children:[{}]}]

here is the code

prepareJson() {

this.service.getComps().subscribe(res =>{
  var comps = res;
  var that = this;
 
 for(var element of comps) {
 
 that.service.getChilds(element._id).subscribe((res1:any)
 =>{
 
 if(res1.length>0)
 
   list.push({name:element.name,children:res})
 },err => console.log(err));
 }


},err => console.log(err));
}

   

Please help.

Siddhartha Gupta

To fix the above code firstly your function should either return an Observable/Promise, as HTTP calls are async.

Also, you can use 'mergeMap' to resolve the further issues you are facing. An example would be something like (Note: Code is untested)

import { Observable, from, EMPTY, Subject } from 'rxjs';
import { mergeMap, finalize, catchError } from 'rxjs/operators';


private prepareJson(): Observable<T> {
const response$ = new Subject<T>();

this.service.getComps().subscribe(res => {
    const comps = res;

    from(comps)
    .pipe(
        mergeMap((element: any) => {
        return this.service.getChilds(element._id)
            .pipe(
            catchError(err => {
                console.log(err);
                return EMPTY;
            })
            );
        }),
        finalize(() => {
        response$.next(list);
        response$.complete();
        }),
    ).subscribe((res1: any) => {
        if (res1.length > 0) {
        list.push({ name: element.name, children: res });
        }
    });
}, (err) => {
    console.log(err);
    response$.error(err);
    response$.complete();
});

return response$.asObservable();
}

Here, 'prepareJson' is return an observable to outside world. We are fetching the result from 'getComps' and on basis of it we are fetching it childs. Once all results are retrieved were are triggering the result via observable.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related