【发布时间】:2017-07-20 13:30:44
【问题描述】:
我目前正在努力解决可观察的问题。我想我没有正确理解 rxjs 的主要概念。这就是我想要实现的目标。
在我的 Angular 应用程序中,有一条 /product/:slug 路由指向 ProductShowComponent。为了显示所有必要的信息,我首先需要使用我的ProductsService 从 API 中获取所有产品。关键是,可能会在组件加载后(例如,当用户在/product/:slug 上刷新页面时)获取产品。
我要做的是在productsService 中实现onReady 方法,在ProductShowComponent 中订阅它,并在从API 获取信息后显示产品。我认为如果onReady 方法返回一个Observable 来监视productsService.ready 值的变化,那么它可能是可能的,但我不知道如何做到这一点,或者它是否可能。也许有更好的方法来做到这一点?有什么想法吗?
product-show.component.ts
(...)
public ngOnInit(): void {
this.route.params.subscribe(params => {
this.productsService.onReady().subscribe(() => {
this.product = this.productsService.get(params['productSlug'], 'slug')
})
})
}
(...)
products.service.ts
(...)
constructor(
private appClient: AppClient
) {
this.fetchAll().subscribe((products: Product[]) => {
this.products = products
this.ready = true
})
}
(...)
public onReady(): Observable<any> {
if (!this.ready) {
// return an observable that watches for changes of value of this.ready
} else {
return Observable.of(null)
}
}
(...)
【问题讨论】:
-
你考虑过使用路由解析器保护吗?它确保在加载组件之前存在一些数据。文件:angular.io/guide/router#resolve-pre-fetching-component-data
标签: javascript angular rxjs observable angular2-observables