Angular 5 nested http client observables return object

五迷三道 提交于 2019-12-11 11:04:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!