通常如何将调用链接到 ng2-Translate 和 rxjs observables?

How to chain calls to ng2-Translate, and rxjs observables in general?

我刚刚开始在我的 Ionic 2 (Angular 2) 项目中使用 ng2 翻译。我发现当我需要一次获取几个字符串时,代码会嵌套并且更难阅读。我有点想知道为什么像这样的东西(只发出一个值)需要使用一个可观察的,但也许有一个很好的理由。无论如何...

例如,假设我有 4 个字符串要在一个方法的不同位置读取

let result1: string;
let result2: string;
let result3: string;
let result4: string;

this.translate.get("key1").subscribe(value1 => {
    result1 = value1;
    this.translate.get("key2").subscribe(value2 => {
        result2 = value2;

        // do some other stuff, which may have another observable returned so yet another level of nesting)

        this.translate.get("key3").subscribe(value3 => {
            result3 = value3;

            // do some other stuff

            this.translate.get("key4").subscribe(value4 => {
                result4 = value4;
            }
        }
        ...

现在假设有超过 4 个字符串。此外,当中间有其他代码时(例如,我也可以将 Ionic 存储称为 returns 一个 Observable),代码变得非常嵌套 - 并且没有错误处理。

所以,问题是:是否有 "flatter" 方法来做到这一点?是否有任何链接(即使类似于 Promise“链接”),可能包括错误处理(即使有某种顶级 catch 块)

我看过其他链接示例,但它们似乎更多地使用运算符而不是像上面那样的大量可观察值。

您不必将它们链接在一起;你可以使用 combineLatest 来组合观察值:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/combineLatest';

Observable.combineLatest(
    this.translate.get("key1"),
    this.translate.get("key2"),
    this.translate.get("key3"),
    this.translate.get("key4")
)
.subscribe(([result1, result2, result3, result4]) => {
    console.log(result1);
    console.log(result2);
    console.log(result3);
    console.log(result4);
});

如果您预先知道所有键值,则可以使用 translate.get() 重载,它接受一个字符串数组...

因此:

this.translate.get(['key1','key2','key3','key4'])
    .subscribe(keys => {
        console.log(keys.key1);
        console.log(keys.key2);
        console.log(keys.key3);
        console.log(keys.key4);
});