我刚刚开始在我的 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 存储,它也返回一个 Observable),代码变得非常嵌套 - 而且没有错误处理。
那么,问题是:有没有一种“更平坦”的方式来做到这一点?是否有任何链接(即使类似于 Promise“链接”),也许包括错误处理(即使有某种顶级 catch 块)
我见过其他链接的例子,但它们似乎更多地使用运算符而不是像上面那样的大量可观察量。
你不必把它们拴起来;您可以使用combineLatest http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-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);
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)