gpt4 book ai didi

angular - 使用 forkjoin 合并 http observables

转载 作者:太空狗 更新时间:2023-10-29 16:51:31 25 4
gpt4 key购买 nike

我试图通过使用 forkjoin 来避免嵌套的 observable。当前(嵌套)版本如下所示:

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

我可以将第一部分重写为:

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_changesdata_all

看另一个例子,我知道它应该看起来像 .subscribe(res => this.combined = {friends:res[0].friends, customer:res[1]});,但我不确定如何使它适应我的示例。

最佳答案

尝试使用 combineLatest 而不是 forkJoin :

使用 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 会在所有调用结束后返回数据并返回 result ,但是在 combineLatest 中任何一个 observable 发出一个值时,从每个 observable 发出最新的值。

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

调用两者并检查控制台日志,您就会明白。

关于angular - 使用 forkjoin 合并 http observables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43166214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com