![](/img/trans.png)
[英]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.