[英]How to run observable depends on previous observable's result with RxJS in Angular?
[英]RxJS Observable result from an Observable's output
我有一个 Angular 8 应用程序,它使用两层来存储数据: StorageService
抽象出实际的 HTTP 服务调用,而它本身不包含除get
和save
各种数据类型之外的其他方法。
BookmarkService
等其他服务使用StorageService
并实现更复杂的业务逻辑,例如添加新的书签文章。
问题是,我们可能必须调用StorageService
两次,以加载数据然后保存它。
我想正确地向调用者站点公开潜在的错误,我想知道实现这样的事情的最佳解决方案是什么,根本不引入 RxJS Subject 对象。 例如,有没有办法仅通过管道来实现这一目标? 有人可以给我一个关于如何正确实现这种模式的例子吗?
export class BookmarkService {
constructor(private storageService: StorageService) {}
addArticleToBookmarks(article: Article): Observable<SaveResponse> {
this.storageService.getBookmarkedArticles().subscribe(articles =>
articles.push(article);
this.storageService.saveBookmarkedArticles(articles).subscribe(saveResponse => ...)
});
// want to return an Observable of saveResponse, if getBookmarkedArticles completed,
// or the error output of getBookmarkedArticles if it failed
return ...
}
你的意思是这样的吗?
addArticleToBookmarks(article: Article): Observable<SaveResponse> {
this.storageService.getBookmarkedArticles()
.pipe(
catchError(err => console.error(err))
switchMap(articles => {
articles.push(article);
return this.storageService.saveBookmarkedArticles(articles);
}
).subscribe(saveResponse => ...)
}
您可以使用switchMap或mergeMap (也称为flatMap
)运算符。
这是关于两者之间差异的一个很好的解释: https : //javascript.tutorialhorizon.com/2017/03/29/switchmap-vs-flatmap-rxjs/
使用switchMap
示例:
addArticleToBookmarks(article: Article): Observable<SaveResponse> {
return this.storageService.getBookmarkedArticles().pipe(
switchMap(articles => {
articles.push(article);
return this.storageService.saveBookmarkedArticles(articles)
})
);
}
我还没有测试过,但我很确定,这会奏效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.