angular - 来自 Observable 输出的 RxJS Observable 结果
问题描述
我有一个 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 => ...)
}
推荐阅读
- angular - InnerHtml 注入带有相对 href 的静态 html
- python - Plotly:如何在子图中添加箭袋?
- reactjs - 我们如何在 react-admin 中设置 React RRule Generator 的默认值?
- c++ - OpenCL 内存带宽/合并
- c# - 需要 for 循环而不是嵌套的 if 语句
- flutter - 如何创建卷曲页面
- python - 在Django中获取外键的所有外键
- puppeteer - 使用 puppeteer 从匿名函数中提取 JSON 数据
- webpack - Webpack 4 和 Pug 不显示图像
- laravel - 我收到对未定义方法 App\Models\User::identifiableAttribute() 的 BadMethodCallException 调用