【问题标题】:Async call not working when calling service - Angular 8调用服务时异步调用不起作用 - Angular 8
【发布时间】:2021-08-19 00:51:44
【问题描述】:

在使用httpClient,post方法调用API服务时,同步不起作用,不等待响应返回

组件.ts

this.juiciosService.createJuicio(this.juicio).then(
    (res: any) => {
      if(res.ok == 200){
        Swal.fire({
          //position: 'top-end',
          icon: 'success',
          title: 'Cedula agregada con exito',
          showConfirmButton: false,
          timer: 2000
        })
        this.detalleJuicio(res.data)
      }
      else {
        Swal.fire({
          //position: 'top-end',
          icon: 'success',
          title: 'No se pudo agregar la cedula',
          showConfirmButton: false,
          timer: 2000
        })
      }
      this.spinnerService.hide();
    }
  )

service.ts

  async createJuicio(juicio): Promise<Juicio> {
    console.log(juicio);
    const url = this.API_URL + 'juicios/Crearjuicios/';
    return await this.http
      .post<Juicio>(url, juicio).toPromise()
      .then(res => res)
  }

【问题讨论】:

  • 因为你使用的是 Promise#then 回调,所以你根本不需要 async/await。

标签: angular asynchronous promise httpclient angular7


【解决方案1】:

您可以将代码更改为:

async methodName()
{
  let res = await this.juiciosService.createJuicio(this.juicio);
  if(res.ok == 200){
     Swal.fire({
          //position: 'top-end',
          icon: 'success',
          title: 'Cedula agregada con exito',
          showConfirmButton: false,
          timer: 2000
     });
     this.detalleJuicio(res.data)
  }
  else{
   
   Swal.fire({
          //position: 'top-end',
          icon: 'success',
          title: 'No se pudo agregar la cedula',
          showConfirmButton: false,
          timer: 2000
        })
    
  }
}

这样它就可以作为一个异步函数工作。

另外,不要忘记对其中一个函数进行异常处理。因为似乎如果您的 HTTP 调用失败,Spinner 将不会隐藏。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多