如何将调用链接到ng2-Translate和rxjs observables? [英] How to chain calls to ng2-Translate, and rxjs observables in general?

查看:224
本文介绍了如何将调用链接到ng2-Translate和rxjs observables?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have just started using the ng2 translate in my Ionic 2 (Angular 2) project. I Have found that when I need to get a few strings all at once, the code becomes nested and a lot harder to read. I am sort of wondering why something like this (that just emits a single value) need to use an observable, but perhaps there is a good reason. Anyway...

例如,假设我在一个方法的不同点读取了4个字符串

So for example, say I had 4 strings to read at various points in a method

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存储器,它也返回一个Observable),代码变得非常嵌套 - 而且没有错误处理。

Now imagine there is more than 4 string. Also when there is other code inbetween this (eg I May also call the Ionic storage which also returns an Observable), the code is getting very nested - and this is with no error handing.

所以,问题是:有没有更平坦的方法来做到这一点?有没有链接(即使类似于承诺链接,可能包括错误处理(即使有某种顶级捕获块)

So, the question is: is there a "flatter" way to do this? IS there any chaining (even if similar to a Promise "the chaining), perhaps including error handling (even if there was some kind of top level catch block)

我看过其他链接的例子,但他们似乎使用运算符而不是像上面这样的大量可观察量来做更多的事情。

I have seen other example of chaining, but they seem to do more with operators rather than lot of observables like the above.

推荐答案

你不必将它们链接起来;你可以使用 combineLatest 结合可观察量:

You don't have to chain them; you can use combineLatest to combine the 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);
});

这篇关于如何将调用链接到ng2-Translate和rxjs observables?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆