我一直在碰我无法解决的RxJS问题。
// pseudocode
http-request ->
do-another-http-request ->
returned combined result
// - chain is always triggered from the outer observable
// - chain completes after each cycle
我要解决的问题稍有不同,因为它尚未完成,但是具有相同的可观察的链式特性。
blog-post_with_category:
-> on-category-id-change
-> return observable of category from datastore
// As shown above, the blog post could either be switched
// to a new category (category_id:6 -> category_id:7)
//
// OR the category itself could change in the datastore i.e. a
// category with a particular id could have an updated
// label (id:3, label:'Sailing' -> id:3, label:'Nautical')
export class BlogPostClass{
postData: PostData
category$: Observable<Category | undefined>
private categoryId$: Subject<string>
constructor(postData:PostData, categoriesQuery: CategoriesService){
// Create an observable for the category ID
this.categoryId$ = new Subject()
// update the data & trigger ID to emit
this.update(postData)
// Chained observable ?? ------------------------
this.category$ = this.categoryId$.pipe(
mergeMap((newCategoryId:string) =>
// observable of category from datastore
this.categoriesQuery.selectEntity(newCategoryId)
)
)
//-----------------------------------------------
}
// ensure that new category ID is emitted on update
update(postData:PostData):void{
this.postData = postData
this.categoryId$.next(postData.category_id)
}
}
订阅生成的链式观察者表明,它在外部观察者更新时更新,而在内部观察者更新时不更新:
post = new BlogPost(postData)
post.category$.subscribe((newCategory) =>
console.log('label: ' + newCategory.label)
)
post.update( {category_id: newValue } )
=> label: new category label
post.category.update( {label: 'different label'} )
// nothing is printed into the console
缺少什么?
this.category$ = this.categoryId$.pipe(
mergeMap((newCategoryId:string) =>
this.categoriesQuery.selectEntity(newCategoryId)
)
)