angular - 如何在内部可观察对象被重建的地方创建 RxJS 链式可观察对象
问题描述
我一直在努力解决我无法弄清楚的 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)
}
}
外部 observable 触发更新,但内部不触发
订阅生成的链式观察者表明它会在外部观察者更新时更新,但在内部观察者更新时不会更新:
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)
)
)
解决方案
推荐阅读
- events - 命令 ID 与基础设施消息 ID 有何不同?
- javascript - 拒绝直接访问 IIS Web 服务器中的 JavaScript 文件
- git - git - 如何从远程存储库中获取特定文件
- javascript - 在嵌入的 PDF、Javascript 中插入超链接
- python - 在调整框架大小时克服自定义 ButtonFrame 的缓慢按钮和框架显示以及不完整的背景。
- react-native - 使用 moment.js 计算睡眠时间并做出本机反应。
- angular - 是否可以将动态值传递给 Angular 6 中的自定义表单验证器?
- python - Use an array as the index of another array in Python
- amazon-web-services - EC2 CLI docker 中可用的 AWS ECR 映像
- php - 弄清楚如何为过滤器循环合并数组