【问题标题】:Synchronous Network request inside foreach and subscribeforeach 中的同步网络请求和订阅
【发布时间】:2019-09-13 18:26:34
【问题描述】:

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

我尝试过使用异步等待但没有成功,我认为由于嵌套类型它不起作用

//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 在控制台中返回。

【问题讨论】:

标签: angular rxjs angular8


【解决方案1】:

试试这个

//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

【讨论】:

  • 开关映射出错The 'this' context of type 'void' is not assignable to method's 'this' of type 'Observable&lt;{}&gt;'.
  • @Napster 你能在 stackblitz 中创建示例并分享吗?
  • stackblitz.com/edit/angular-crxo3g 给你,先生,请把我拉出来。
  • @Napster 更新示例。现在您将收到两个值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-31
相关资源
最近更新 更多