Angularfire2如何在angular4-5中处理多个Observable

时间:2018-06-14 10:29:03

标签: angular observable angularfire2

在执行函数之前从多个observable获取数据的最佳方法是什么

实施例

provider.ts

obs1 = this.afDB.object(`app/radio`).snapshotChanges();
obs2 = this.afDB.object(`app/users`).snapshotChanges();
obs3 = this.afDB.object(`app/song`).snapshotChanges();

app.ts

doSomething(){

console.log('this is my', ${radio}, 'it plays on this date:' ,${date}, 'this song', ${song}`);

}

我将订阅放在彼此之内......它可以工作但是......处理这种异步行为的正确方法是什么?

doSomething(){

provider.obs1.subscribe(val1 =>{
provider.obs2.subscribe(val2 =>{
provider.obs3.subscribe(val3 =>{

 console.log('this is my', ${val1.payload.val().radio}, 'it plays on this date:' ,${val2.payload.val().date}, 'this song', ${val3.payload.val().song}`);

});
});
});

    }

1 个答案:

答案 0 :(得分:1)

使用 forkJoin 运算符。

doSomething(){
   Observable.forkJoin(
      provider.obs1,
      provider.obs2,
      provider.obs3
   ).subscribe(data => {
       console.log("values: ",data[0], data[1], data[2]) 
   }, err => {
       console.log("Handle error here");
   })
}