我正在尝试通过使用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();
      });
    });
  }

我可以将第一部分重写为:
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中,当任何可观察到的对象发出值时,从每个对象中发出最新值。

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/

10-10 13:34