如何从 Angular 2 / Ionic 3 中的多个 Observable 执行错误处理?

How to perform error handling from multiple Observables in Angular 2 / Ionic 3?

我正在尝试在 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 for forkJoin 将为每次失败执行。我想要的是只显示一次吐司通知。

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

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

并且您可以添加您的 catch,如果其中一个可观察对象抛出异常,该 catch 将被调用一次。