angular - 为什么订阅无法读取 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。
希望你们能帮助我:)
解决方案
您可以避免异步 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 非常强大。我避免了所有的异步等待,并且只在我的应用程序中使用它们,我从中获得了很多乐趣!
推荐阅读
- java - 使用java Spring将值注入Hashmap
- html - 用模板上的 CDN 替换供应商的文件是一种好习惯吗?
- c# - 读取数据集合
使用 C# 从 Dynamics CRM - sql - 比较具有最大值的列,并根据列名分配值
- apache - 无法使用 modsecurity 和核心规则集阻止暴力攻击的 IP 地址
- ip - 带有主动健康检查的 istio 负载均衡服务入口
- python - 将烧瓶压缩添加到 py2exe 可执行文件
- xaml - 创建 2 列 UPW ListView 的正确方法是什么?
- google-play - 如何使用 Google Play 回复评论 API 获取评论提交时间?
- postgresql - PostgreSQL 中 WHERE 子句中的可空布尔检查