Angular 5 嵌套 http 客户端 observables 返回对象 [英] Angular 5 nested http client observables return object
问题描述
我正在尝试创建一个可观察的响应,其中我进行了一次 http 调用,然后在返回响应之前,我进行了另一个 http 调用以填充第一个调用的返回对象,如下所示.
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;
}
)
});
}
编译器给出错误:类型'Observable'不可分配给类型'Observable'.不知道如何让这个工作.this.getOrder() 和 this.searchItems() 都映射了返回相应 observables 的 http 调用.
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.
推荐答案
你的 map 没有返回任何东西.它只订阅另一个 Observable.
Your map doesn't return anything. It only subscribes to another Observable.
要将一个 Observable 转换为另一个 Observable(getOrder 到 searchItems),请使用平面运算符之一.在您的情况下,switchMap 适合:
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}))
);
这篇关于Angular 5 嵌套 http 客户端 observables 返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!