Merging http observables using forkjoin

后端 未结 1 443
时光说笑
时光说笑 2020-12-01 03:06

I\'m trying to avoid nested observables by using forkjoin. The current (nested) version looks like this:

  this.http.get(\'https://testdb1.fireb         


        
相关标签:
1条回答
  • 2020-12-01 03:24

    Try to use combineLatest instead of forkJoin :

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

    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.

    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.

    0 讨论(0)
提交回复
热议问题