【问题标题】:How to chain calls to ng2-Translate, and rxjs observables in general?通常如何链接对 ng2-Translate 和 rxjs 可观察对象的调用?
【发布时间】:2017-01-19 01:39:46
【问题描述】:

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

例如,假设我有 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 个字符串。此外,当在这之间有其他代码时(例如,我也可以调用也返回 Observable 的 Ionic 存储),代码变得非常嵌套 - 这没有错误处理。

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

我见过其他链接的例子,但他们似乎更多地使用操作符而不是像上面的许多可观察对象。

【问题讨论】:

    标签: angular ionic2 rxjs ng2-translate


    【解决方案1】:

    你不必把它们锁起来;你可以使用 combineLatest 来组合 observables:

    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);
    });
    

    【讨论】:

    • 以上效果很好,但我在捕获错误时遇到了问题。已在新的post 中打开此内容。
    【解决方案2】:

    如果您事先知道所有键值,则可以使用 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);
    });
    

    【讨论】:

      猜你喜欢
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      • 2021-08-26
      • 2022-11-09
      • 2020-12-22
      • 2015-01-12
      • 2016-06-18
      相关资源
      最近更新 更多