问题
I am trying to create an observable response where I make one http call and then before returning the response, I make another http call to populate the return object of the first call as shown below.
getOrderWithItems(orderId: string, includes: Set<OrderInclude>): Observable<OrderDto> {
return this.getOrder(orderId, includes)
.map(order => {
this.searchItems().subscribe(
items => {
order.items = items.results;
return order;
}
)
});
}
The compiler gives an error: Type 'Observable' is not assignable to type 'Observable'. Not sure how to get this to work. this.getOrder() and this.searchItems() both map http calls which return corresponding observables.
回答1:
Your map doesn't return anything. It only subscribes to another Observable.
For transforming one Observable into another (getOrder to searchItems), use one of the flat Operators. In your case, switchMap would fit:
this.getOrder(orderId, includes)
.switchMap(order =>
this.searchItems()
.map(items => ({...order, items: items.results}))
);
来源:https://stackoverflow.com/questions/49101448/angular-5-nested-http-client-observables-return-object