Angular 嵌套服务中的嵌套可观察对象 - 如何
Angular nested observable's in nested services - how to
我知道如何在同一个 component/service 中执行嵌套的 observable 。
或者如何 return 从服务到组件的可观察对象。但是我如何从一个可观察服务获取数据到我的组件中,从另一个可观察服务获取数据:
一个简化的场景:
我有一个 APIService,它 return 通过 observable 发送我的数据:
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 分开
但是我得到一个错误 Type 'Subscription' is not assignable to type 'Observable'. in ProductService subscribe
而且我已经尝试了从管道到映射的所有方法,而不是订阅...
ProductService
必须 return 一个 Observable
。这意味着您不能在 doCalcWithProducts()
方法内订阅。
您应该通过 map 函数传递 stockApiService.getProduct()
结果。像这样:
export class ProductService {
doCalcWithProducts(): Observable<any> {
return stockApiService.getProduct().pipe(
map(products => this.doMoreCalcWithproducts(products))
);
}
}
我知道如何在同一个 component/service 中执行嵌套的 observable 。 或者如何 return 从服务到组件的可观察对象。但是我如何从一个可观察服务获取数据到我的组件中,从另一个可观察服务获取数据:
一个简化的场景:
我有一个 APIService,它 return 通过 observable 发送我的数据:
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 分开
但是我得到一个错误 Type 'Subscription' is not assignable to type 'Observable'. in ProductService subscribe
而且我已经尝试了从管道到映射的所有方法,而不是订阅...
ProductService
必须 return 一个 Observable
。这意味着您不能在 doCalcWithProducts()
方法内订阅。
您应该通过 map 函数传递 stockApiService.getProduct()
结果。像这样:
export class ProductService {
doCalcWithProducts(): Observable<any> {
return stockApiService.getProduct().pipe(
map(products => this.doMoreCalcWithproducts(products))
);
}
}