foreach 和订阅中的同步网络请求

Synchronous Network request inside foreach and subscribe

我需要的是从一个 api 获取数据,然后将其发送给另一个并附加值。

我试过使用 async await 但没有成功,我认为由于嵌套类型它不起作用

//service.ts
getRecentBackups();
{
  return this.http.get<any[]>(
    `${environment.URL}`
  );
}

getAccounts(accountId);
{
  return this.http.get(
    `${environment.URL}/${accountId}`
  );
}

//component.ts
this.abc.getRecentBackups().subscribe(data => {
  const backupData = data['activities'];
  backupData.forEach(activity => {
    const alert = new Alert();
    //Problem here need to extract response first
    let response = this.abc.getAccounts(activity['accountNum']);
    this.longRunningAlerts.push(alert);
    this.backupAlerts.push(alert);
  });
   //this should execute after above is done.
  this.totalRecentStatus = backupData.length;
  this.longRunningAlerts = [...this.longRunningAlerts];
  this.backupAlerts = [...this.backupAlerts];
}

此处演示:https://stackblitz.com/edit/angular-crxo3g

Observable 在控制台返回。

试试这个

//service.ts
getRecentBackups();
{
  return this.http.get<any[]>(
    `${environment.URL}`
  );
}

getAccounts(accountId);
{
  return this.http.get(
    `${environment.URL}/${accountId}`
  );
}

//component.ts
 this.appService.getRecentBackups().pipe(
      map(data => data['activities']),
      map(backupData => backupData.map(activity => {
        return this.appService.getAccounts(activity['accountNum']).pipe(
          map(res => ({ activity: activity, account: res }))
        )
      })),
      switchMap(apiRequest => zip(...apiRequest))
    ).subscribe(result => {
      // this.backupAlerts.push({ activity: activity, account: response });
      console.log(result);
      this.backupAlerts = [...this.backupAlerts];
      console.info('Backup Alerts', this.backupAlerts)
    })

Rxjs Zip

SwitchMAp

Map