首页 > 解决方案 > 为什么订阅无法读取 api 响应

问题描述

我正在尝试使用一种使用其 ID 号为我带来用户信息的方法

组件.ts

identificacion:any = this.route.snapshot.paramMap.get('identificacion');
  
  constructor(private route: ActivatedRoute, private dataService: DataService) { 
  }

  async ngOnInit() {
    await this.dataService.getParticipeByIdentificacion(this.identificacion).subscribe(resonse => console.log(resonse))
    }

服务调用:

getParticipeByIdentificacion(id) {
    this.tokenvalido();
    const token = this.getToken();
    return this.http.get(`${this.apiUrl}/participe/identificacion/${id}`);
  }

来自 api 的响应:

{
  "result": {
    "actividadEconomica": null,
    "genero": "Masculino",
    "estadoCivil": "SOLTERO",
    "contratos": [],
    "contactos": [],
    "direcciones": [],
    "referenciasPersonales": [],
    "referenciasBancarias": [],
    "idParticipe": 195,
    "idTipoIdentificacion": 1,
    "tipoIdentificacion": null,
    "identificacion": null,
    "nombres": "WILMER JAVIER",
    "apellidos": "DECIMAVILLA ESPINOZA",
    "razonSocial": "WILMER JAVIER DECIMAVILLA ESPINOZA",
    "fechaRegistro": "2021-02-08T19:57:30.277",
    "fechaModificacion": "2021-05-12T11:39:31.413",
    "usuarioRegistro": "SYSTEM",
    "usuarioModificacion": "",
    "estado": "Aprobado",
    "fechaNacimiento": "",
    "lugarNacimiento": "N/A",
    "idNacionalidad": 1,
    "fechaExpedicionCedula": "0001-01-01T00:00:00",
    "correo1": null,
    "correo2": null,
    "telefono1": null,
    "telefono2": null,
    "celular": null,
    "idGenero": 1,
    "idEstadoCivil": 1,
    "idNivelEstudios": 3,
    "idNivelIngresos": 2,
    "idProfesion": 1,
    "idGrado": 102,
    "identificacionConyuge": null,
    "conyuge": null,
    "idTipoVivienda": 1,
    "tiempoResidencia": 1,
    "photoUrl": null,
    "codigoUniformado": null,
    "fechaIngreso": "2010-10-21T00:00:00",
    "aporteAdicional": 0,
    "observaciones": null
  },
  "error": null,
  "message": "El servidor respondio con el codigo de estado: 200 OK",
  "statusCode": "OK",
  "success": true
}

我得到的错误:

错误类型错误:您在预期流的位置提供了“未定义”。您可以提供 Observable、Promise、Array 或 Iterable。

希望你们能帮助我:)

标签: angular

解决方案


您可以避免异步 ngOnInit 并仅使用带有isLoad标志的 observables。

  identificacion:any;
  isLoad: boolean;
  subscriptions = new Subscription
  constructor(private route: ActivatedRoute, private dataService: DataService) { 
  }

 ngOnInit() {
  this.identification = this.route.snapshot.paramMap.get('identificacion');

  const stream = this.dataService.getParticipeByIdentificacion(this.identificacion).pipe(
    tap((res) => console.log(res))
  .subscribe(() => this.isLoad = true)

  this.subscription.add(stream)
  }


 ngOnDestroy() {
  this.subscriptions.unsubscribe() //remember to unsuscribe 
 }

然后您可以仅在有数据时使用您的标志来呈现页面

<ng-container *ngIf="isLoad">
 //here your data are load
</ng-container>

rxjs 和 observable 非常强大。我避免了所有的异步等待,并且只在我的应用程序中使用它们,我从中获得了很多乐趣!


推荐阅读