我试图通过使用来避免嵌套的observable forkjoin.当前(嵌套)版本如下所示:
this.http.get('https://testdb1.firebaseio.com/.json').map(res => res.json()).subscribe(data_changes => {
this.http.get('https://testdb2.firebaseio.com/.json').map(res => res.json()).subscribe(data_all => {
/* Do this once resolved */
this.platform.ready().then(() => {
this.storage.set('data_changes', data_changes);
this.storage.set('data_all', data_all);
document.getElementById("chart").innerHTML = "";
this.createChart();
});
});
},
err => {
this.platform.ready().then(() => {
console.log("server error 2");
document.getElementById("chart").innerHTML = "";
this.createChart();
});
});
}
Run Code Online (Sandbox Code Playgroud)
我可以将第一部分重写为:
Observable.forkJoin(
this.http.get('https://testdb1.firebaseio.com/.json').map((res: Response) => res.json()),
this.http.get('https://testdb2.firebaseio.com/.json').map((res: Response) => res.json())
)
Run Code Online (Sandbox Code Playgroud)
但我不知道如何添加.subscribe方法来访问data_changes和data_all.
看另一个例子,我知道它应该看起来像.subscribe(res => this.combined = {friends:res[0].friends, customer:res[1]});,但我不知道如何适应我的例子.
两者都用于连接多个流。
由此 我对两者感到困惑,我读了combineLatest在同步模式下进行调用和forkJoin并行调用,
我正在尝试这个
combineLatest([
of(null).pipe(delay(5000)),
of(null).pipe(delay(5000)),
of(null).pipe(delay(5000))
]).subscribe(() => console.log(new Date().getTime() - start));
forkJoin([
of(null).pipe(delay(5000)),
of(null).pipe(delay(5000)),
of(null).pipe(delay(5000))
]).subscribe(() => console.log(new Date().getTime() - start));
Run Code Online (Sandbox Code Playgroud)
打印
5004
5014
Run Code Online (Sandbox Code Playgroud)
每次结果约为5秒,如果combineLatest按顺序发送请求,那么为什么它打印持续时间约为5秒。
这是正确的还是有其他区别,有示例代码吗?