Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve in Angular for multiple api calls

I am trying to call 3 different APIs before a component loads using the Resolve.

This code below is written inside the resolve function and is returning an object with all response packaged.

Now When The component loads, before I receive the response from server.. it returns null for each of the keys in the object returned.

Please help how do I solve this kinda issue. How do I stop it from returning until the response is not received from the API.

resolve() {
  this._apiFactory.getA().subscribe(response => {
     responseA = response;
  });
  this._apiFactory.getB().subscribe( response => {
     responseB = response;
  });
  this._apiFactory.getC().subscribe( response => {
     responseC = response;
  });

  return {
    'A': responseA ,
    'B': responseb ,
    'C': responseC 
  };
}
like image 760
JEET ADHIKARI Avatar asked Aug 04 '26 08:08

JEET ADHIKARI


1 Answers

You were returning the before your subscriptions could get finished. Used Fork Join to wait until all your Get requests are completed and then returning the result of the get requests in your required format..

Update

Since Rxjs 6.5.0, forkJoin also accepts an object as an argument.

// dummy Observables
const obsArg = {
    A: of([1]).pipe(delay(1000)),
    B: of([1, 2, 3]).pipe(delay(2000)),
    C: of([1, 2, 3, 4]).pipe(delay(3000))
}

return forkJoin(obsArg)

I tried it in Angular 6 and I was able to do it like:

// dummy Observables
let a  = of([1]).pipe(delay(1000));
let b  = of([1, 2, 3]).pipe(delay(2000));
let c  = of([1, 2, 3, 4]).pipe(delay(3000));

 let join = forkJoin(a,b,c).pipe(map((allResponses) => {
   return {
     A: allResponses[0],
     B: allResponses[1],
     C: allResponses[2]
   };
 }));

 return join;

So, I manipulated the data in forkJoin and returned the forkJoin itself. see it here: https://stackblitz.com/edit/angular-xepafp?file=src%2Fapp%2FAPIResolver.ts

In angular2, something like this should work:

resolve() {
    return Observable.forkJoin(
      this._apiFactory.getA(),
      this._apiFactory.getB(),
      this._apiFactory.getC()
    ).map((allResponses) => {
       return {
         A: allResponses[0],
         B: allResponses[1],
         C: allResponses[2]
       };
     })
}
like image 144
Ashish Ranjan Avatar answered Aug 06 '26 22:08

Ashish Ranjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!