繁体   English   中英

Angular 9 - 如何将 2 http.get 合并为一个 Observable

[英]Angular 9 - how to merge 2 http.get into one Observable

我使用 Angular 9 并希望将来自后端的 2 个结果合并为一个。 我目前的方法:

protected getDataSource(): Observable<AgentSummary> | Refresher<any, AgentSummary> {
  return this.groupSelector.selectedGroup$.pipe(e =>
    filter(Boolean),
    switchMap((group: SelectedGroup) => this.dashboardHttp.getAgentsStatus(group.id))
  );
}

我想调用额外的 http.get 并将其合并

switchMap((group: SelectedGroup) => this.dashboardHttp.getAgentsStatus(group.id))

:

getRecoveryPoints(groupId: string): Observable<BackupSummary> {
  const headers: HttpHeaders = getHeaders(groupId);

    return this.http.get<BackupSummary>(`${this.env.URI}/backup/api/v1/dashboard/recovery-point`, {
    headers: headers,
  });
}

怎么做? 我是 Angular 的新人,所以请理解我:)

rxjs function combineLatest应该是您所需要的,您可以在此处阅读更多相关信息。

combineLatest([
  this.getDataSource(),
  this.getRecoveryPoints(groupId)
]).subscribe(([dataSource, recoveryPoints]) => {
  // do something
})

要组合两个 rest 调用,您可以使用combineLatest中的rxjs

例子:

combineLatest([
   this.dashboardHttp.firstCall(),
   this.dashboardHttp.secondCall()
]).subscribe(([firstCallResponse, secondCallResponse]) => {
   console.log(firstCallResponse);
   console.log(secondCallResponse);
});

这样您就可以合并来自后端的两个调用。

您可以通过多种方式组合 http 调用或任何其他类型的observables对象,我最喜欢使用combineLatest这里是文档:

let getDataSource$ = getDataSource();
let getRecoveryPoints$ = getRecoveryPoints();

combineLatest(getDataSource$, getRecoveryPoints$, 
  (dataSource, recoveryPoints) => ({dataSource, recoveryPoints})
    .subscribe( results => {
       let ( dataSource, recoveryPoints) = result;
         ... // do your stuff with the results
    })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM