Home > Back-end >  Refactor nested API calls with RxJS
Refactor nested API calls with RxJS

Time:02-12

Here's what I need to refactor:

  1. Call API/GetUser, get result, extract user.id, save result (user)
  2. Call API/GetMoreUserData/{userId} with id from first call, save result (moreData)
  3. Construct object with both results {u: user, d: moreData } and return it to the caller

I'm currently using nested calls to accomplish this, but I'm sure there's a better way of doing it with RxJS.

CodePudding user response:

This is what switchMap is for.

@Injectable({ providedIn: 'root' })
export class UserService {
  getUser(): Observable<any> {
    //mock implementation, probably would be an HTTP get
    return of({ id: 42 });
  }

  getMoreUserData(id: number): Observable<any> {
    //mock implementation, probably would be an HTTP get
    return of({ username: 'batman', id: id });
  }

  getAllTheUserData(): Observable<any> {
    return this.getUser().pipe(
      switchMap((userResp) => {
        const userId = userResp.id;

        return this.getMoreUserData(userId).pipe(
          map((moreUserResp) => {
            //spread operator to combine to two objects
            return {
              ...userResp,
              ...moreUserResp,
            };
          })
        );
      })
    );
  }
}

Here's a stackblitz demonstrating the service and it's usage.

CodePudding user response:

You can use pipe and switchMap, here is a random example:

this.activatedRoute.params.pipe(                            //params returns an observable
      switchMap(({id}) => this.buyerService.getDetails(id)) //getDetails returns an observable
    )
    .subscribe(h => {
      console.log(h)
}
  • Related