首页 > 解决方案 > 来自 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 ...

  }

标签: angularrxjsobservable

解决方案


你的意思是这样的吗?

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 => ...)

}

推荐阅读