Reputation: 26521
Here's what I need to refactor:
API/GetUser
, get result, extract user.id
, save result (user
)API/GetMoreUserData/{userId}
with id
from first call, save result (moreData
){u: user, d: moreData }
and return it to the callerI'm currently using nested calls to accomplish this, but I'm sure there's a better way of doing it with RxJS.
Upvotes: 1
Views: 2468
Reputation: 2708
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.
Upvotes: 4
Reputation: 116
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)
}
Upvotes: 0