问题描述
我试图通过使用 forkjoin
来避免嵌套的 observables.当前(嵌套)版本如下所示:
I'm trying to avoid nested observables by using forkjoin
. The current (nested) version looks like this:
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();
});
});
}
我可以将第一部分改写为:
I can rewrite the first part as:
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())
)
但我不确定如何添加 .subscribe
方法来访问 data_changes
和 data_all
.
But i'm not sure how I would then add the .subscribe
method to access both data_changes
and data_all
.
再看另一个例子,我知道它应该类似于 .subscribe(res => this.combined = {friends:res[0].friends, customer:res[1]});代码>,但我不确定如何使其适应我的示例.
Looking at another example, I know it should look something like .subscribe(res => this.combined = {friends:res[0].friends, customer:res[1]});
, but i'm not sure how to adapt this to my example.
推荐答案
尝试使用 combineLatest
代替 forkJoin
:
Try to use combineLatest
instead of forkJoin
:
与 combineLatest
:
With combineLatest
:
const combined = Observable.combineLatest(
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())
)
combined.subscribe(latestValues => {
const [ data_changes , data_all ] = latestValues;
console.log( "data_changes" , data_changes);
console.log( "data_all" , data_all);
});
你也可以通过 forkJoin 来处理,但是 forkJoin 会在所有调用完成后返回数据并返回结果,但是在 combineLatest 中任何一个 observable 发出一个值时,都会从每个中发出最新的值.
You can also handle it by forkJoin , but forkJoin will return data when all calls are finished and return result , but in combineLatest When any observable emits a value, emit the latest value from each.
使用 forkJoin
:
With forkJoin
:
const combined = 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())
)
combined.subscribe(latestValues => {
const [ data_changes , data_all ] = latestValues;
console.log( "data_changes" , data_changes);
console.log( "data_all" , data_all);
});
调用两者并检查控制台日志,你会明白的.
Call both and check the console log , you will get idea.
这篇关于使用 forkjoin 合并 http observables的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!