RxJs 相当于 Promise.all()

dan*_*y74 1 rxjs angular

什么是 Promise.all() 的 RxJs 等价物,其中 then 块仅在所有承诺都得到解决时执行?

const request1 = this.http.get('/api/hello').toPromise() // returns a promise
const request2 = this.http.get('/api/there').toPromise() // returns a promise

Promise.all([request1, request2]).then(([response1, response2]) => {
  // executes if/when ALL the promises resolve
  console.log('response1', response1);
  console.log('response2', response2);
}).catch(err => {
  // executes if ANY ONE of the promises fail / reject
  console.log('err', err);
})
Run Code Online (Sandbox Code Playgroud)

那么 RxJs 中的等效方法是什么?谢谢

Cod*_*-EZ 11

您可以使用forkJoin

当您有一组 observable 并且只关心每个的最终发出值时,最好使用此运算符。您可以使用此运算符发出多个请求。

import { forkJoin, Observable } from "rxjs" ;

用法

const request1 = this.http.get('/api/hello'); //return an observable
const request2 = this.http.get('/api/there') //return an observable

forkJoin([request1,request2]).subscribe((response)=>{

    //after all the successful requests 
    //response.forEach((eachRes)=>{console.log(eachRes)});
    //or response[0] , response[1]


});
Run Code Online (Sandbox Code Playgroud)

  • 或者干脆 .subscribe(([res1,res2]) => {...} (4认同)