Here's what I need to refactor:
- Call
API/GetUser
, get result, extractuser.id
, save result (user
) - Call
API/GetMoreUserData/{userId}
withid
from first call, save result (moreData
) - 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)
}