嵌套服务中的角嵌套可观察对象-如何

时间:2018-08-16 09:51:53

标签: angular rxjs observable angular-services

我有一个想法,如何在同一组件/服务中嵌套可观察的。 或如何将可观察到的东西从服务返回到组件。但是,如何从可观察的服务获取数据到我的组件中,而该服务可从另一个可观察的服务获取数据:

一种简化的情况:

我有一个APIService通过可观察的方式返回我的数据:

export class StockAPIService {
// ...
    getProducts(): Observable<any> {     
        return this.http.get<any>(this.productsUrl);
    }
}

我通常会像在组件中那样使用它:

export class ProductsComponent {
    products = {};
    ngOninit() {
        stockApiService.getProduct().subscribe(products => 
              this.products = doCalcWithProducts(products))
    }

    doCalcWithProducts() {
       // ALLOT of business logic comes here that I want to move to a service
    }
}

所以我想提供如下服务:

export class ProductService {
    doCalcWithProducts(): observable<any> {
        return stockApiService.getProduct().subscribe(products => 
              return doMoreCalcWithproducts(products))
    }
}

然后我的组件实际上只看起来像这样:

export class ProductsComponent {
    products = {};
    ngOninit() {
        this.ProductService.doCalcWithProducts().subscribe(products => 
              this.products = products)
    }
}

...已删除业务逻辑,但仍将我的APIService与我的ProductService分开

但是出现错误无法将类型'Subscription'分配给类型'Observable'。在ProductService中订阅

我已经尝试了从管道到地图的所有操作,而不是订阅...

1 个答案:

答案 0 :(得分:2)

ProductService必须返回Observable。这意味着您无法在doCalcWithProducts()方法内进行预订。

您应该通过地图函数通过管道传递stockApiService.getProduct()结果。像这样:

export class ProductService {
  doCalcWithProducts(): Observable<any> {
    return stockApiService.getProduct().pipe(
      map(products => this.doMoreCalcWithproducts(products))
    );
  }
}