【问题标题】:RxJs 6 - Make 2 http calls and wait for all responsesRxJs 6 - 进行 2 个 http 调用并等待所有响应
【发布时间】:2018-12-27 03:15:05
【问题描述】:
@Effect()    
initDomain$: Observable<Action> = this.actions$.pipe(
  ofType('INIT_DOMAIN'),
  mergeMap((action: any) =>
     this.http.get('https://demo.api/url1.php').pipe(
        switchMap((data) => [
           {type: 'INIT_IT', payload: data}
        ]),
        catchError(() => of({type: 'INIT_IT_FAILED'}))
     )
  )
);

我有这种角度效果 (ngrx),它会在继续之前发出 1 个请求。如何在继续之前发出 2 个请求并等待两个响应?我知道 forkJoin() 是答案,但我对语法有点困惑

【问题讨论】:

标签: rxjs ngrx ngrx-effects fork-join rxjs6


【解决方案1】:
forkJoin(
 this.http.get('myUrl'),
 this.http.get('myOtherUrl')
)

或者如果你在一个数组中有一堆 observables,你也可以写

const myArrayOfObservables = [
  this.http.get('myUrl'),
  this.http.get('myOtherUrl')
];

forkJoin(
  myArrayOfObservables
)

这是因为 "forkJoin" 使用 "spread" (...args) 运算符作为其参数。

【讨论】:

  • 请注意,如果其中一个obs在使用forkJoin时失败,而某些调用可能成功,则整个obs将被视为失败。
猜你喜欢
  • 2017-09-04
  • 2021-12-01
  • 2020-11-03
  • 1970-01-01
  • 1970-01-01
  • 2020-08-21
  • 1970-01-01
  • 1970-01-01
  • 2015-12-28
相关资源
最近更新 更多