我正在尝试使用Ionic 3应用程序中的多个Observable
缓存一些数据:
import { Observable } from "rxjs/Observable";
import 'rxjs/add/observable/forkJoin'
// saves data for a single article
private saveToCache(articleId: number): Observable<any> {
this.loadingCtrl.create({ content: "Caching data. Please wait..." });
this.loadingCtrl.present();
let key = articleId;
let obs = this.articleService.getArticleFullData(key);
obs.subscribe(data => {
this.loadingCtrl.dismiss();
this.cache.saveItem("" + key, data as ArticleFullData);
this.loggingService.logInfo("Cache article: " + key);
},
err => {
this.loggingService.logError("Failed to cache data: " + key);
this.loadingCtrl.dismiss();
var toastObj = this.toastCtrl.create({ message: "Failed to cache data: ", duration: 2000 });
toastObj.present();
}
);
return obs;
}
// handler to perform caching for a list of articles
onCacheRefresh() {
// articles are not loaded for some reason
if (!this.articles)
return;
var obsArray = [];
for (let article of this.articles) {
let key = "" + article.ArticleId;
// already in cache
this.cache.getItem(key)
.then(data => {
console.log("Cache item already exists: ", data);
})
.catch(err => {
obsArray.push(this.saveToCache(article.ArticleId));
});
}
let err: boolean = false;
Observable.forkJoin(obsArray).toPromise()
.catch(err => {
if (err)
return;
err = true;
this.loggingService.logError("Failed to cache data: ", JSON.stringify(err));
var toastObj = this.toastCtrl.create({ message: "Failed to cache data: ", duration: 2000 });
toastObj.present();
});
}
如果由于任何原因,数据提取失败,catch
的{{1}}将针对每次失败执行。我想要的是能够只显示一次吐司通知。
问题:我应该如何处理来自多个forkJoin
的错误?
答案 0 :(得分:1)
您可以尝试使用combineLatest运算符。语法如下所示:
const combinedProject = Rx.Observable
.combineLatest(
timerOne,
timerTwo,
timerThree,
(one, two, three) => {
return `Timer One (Proj) Latest: ${one},
Timer Two (Proj) Latest: ${two},
Timer Three (Proj) Latest: ${three}`
}
);
如果其中一个observable抛出异常,你可以添加一次调用的catch。