簡體   English   中英

來自 Observable 輸出的 RxJS Observable 結果

[英]RxJS Observable result from an Observable's output

我有一個 Angular 8 應用程序,它使用兩層來存儲數據: StorageService抽象出實際的 HTTP 服務調用,而它本身不包含除getsave各種數據類型之外的其他方法。

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

}

您可以使用switchMapmergeMap (也稱為flatMap )運算符。

這是關於兩者之間差異的一個很好的解釋: https : //javascript.tutorialhorizo​​n.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM