【问题标题】:How to make API calls inside a for loop to wait for one to finish before making another in Angular using observables?如何在 for 循环中进行 API 调用以等待一个完成,然后再使用 observables 在 Angular 中创建另一个?
【发布时间】:2021-03-28 15:16:03
【问题描述】:

我有一个 for 循环,如果数组的长度为 6,则根据数组的长度进行一次 API 调用,所以会有 6 次 API 调用,问题是异步调用,所以其中一些给了我错误, 我怎样才能对循环内的每个 API 调用等到它完成后再进行另一个调用?

我真的很想用 observables 而不是 promises 来做

这是我打电话的地方

 respuestaEncuesta(respuesta:any,idEncuesta:number,idPregunta:number){
    return this.http.post(this.API_URL+'api/encuestas/'+idEncuesta+'/preguntas/'+idPregunta+'/respuesta',respuesta,this.httpOptions)
  }

这是我的 for 循环,我在函数中所做的唯一事情是发送数组然后执行循环,这是在我的 ts 上,在这里我调用在服务内部执行 API 调用的函数

for (let j=0;j < this.obj.data.length; j++){
      this.userService.respuestaEncuesta(this.obj.data[j],this.id,this.auxPreguntas[j])
      .subscribe(
        res => {
          let auxRes:any;
          auxRes = res;
          if(auxRes.estado == 'success'){
            console.log('successful call')
          }
        },
        err => {
          console.log(err)
        }
      )
    }

我尝试过这样的 forkjoin,但没有成功,有些请求没有发送

respuesta:any = [];
for (let j=0;j < this.obj.data.length; j++){
this.respuesta.push(this.userService.respuestaEncuesta(this.obj.data[j],this.id,this.auxPreguntas[j])) 
    }
forkJoin(this.respuesta)
    .subscribe(
      results => {
        console.log(results);
      }
    )

【问题讨论】:

标签: angular typescript


【解决方案1】:

您可能正在寻找concatMap

示例

stackblitz:https://stackblitz.com/edit/angular-ivy-ms2yst?file=src/app/app.component.ts

let data = [1, 2, 3];
of(...data)
.pipe(
  // use a concatmap
  concatMap(value => {
    return of(value).pipe(delay(2000)) 
    // this represents your request
  })
)
.subscribe(item => {
  console.log(item);
  // requests should now be made one after another, do whatever
});

【讨论】:

  • 我试过这个并说这个error Observable 类型上不存在属性管道[]
  • 对了。我想这就是你要找的东西:stackblitz.com/edit/angular-ivy-ms2yst?file=src/app/…。我会相应地编辑帖子;)
  • 我放了它,但它不起作用请检查我更新的问题,如果可以的话,请给我一个我的代码示例
  • 您应该准备好数据,这样它就足以创建您的 http 请求的参数。但我相信你可以自己做所有这些。
猜你喜欢
  • 1970-01-01
  • 2014-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-02
  • 1970-01-01
相关资源
最近更新 更多