我正在尝试在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();
        });
}

如果由于某种原因数据获取失败,那么对于每次失败,catchforkJoin将执行。我想要的是只能显示一次Toast通知。

问题:应该如何处理来自多个Observable的错误?

最佳答案

您可以尝试wit 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}`
  }
);

并且您可以添加您的捕获,如果其中一个可观察到的异常抛出,则将被调用一次。

10-02 15:54