Javascript 从observeble HTTP请求的订阅为角度分量中的变量赋值
当我想通过订阅HTTP请求为Angular component中的局部变量赋值时 我没有定义Javascript 从observeble HTTP请求的订阅为角度分量中的变量赋值,javascript,angular,Javascript,Angular,当我想通过订阅HTTP请求为Angular component中的局部变量赋值时 我没有定义 patient: Patient; hpId: any; ngOnInit() { const id = +this.route.snapshot.paramMap.get('id'); this.fetchPatient(id); console.log(this.hpId); } fetchPatient(id: number) { this.pa
patient: Patient;
hpId: any;
ngOnInit() {
const id = +this.route.snapshot.paramMap.get('id');
this.fetchPatient(id);
console.log(this.hpId);
}
fetchPatient(id: number) {
this.patientService.getPatient(id)
.subscribe( data => {
this.patient = data;
this.hpId = this.patient.appointment[0].healthProfessionalId;
});
}
}
我想使用订阅方法范围之外的hpId值
在此之后调用这些方法。hpId=
此.patient.appointment[0].HealthProfessional ID;线路
hdId
,请使用like{{hpId}
2) 如果您想调用另一个API,那么可以将该调用包装在.subscribe()中
fetchPatient(id: number) {
this.patientService.getPatient(id)
.subscribe( data => {
this.patient = data;
this.hpId = this.patient.appointment[0].healthProfessionalId;
this.yourMethod(this.hdId); // here
});
}
yourMethod(hdId){
console.log(hdId); // do whatever with `hdId`
}
组件初始化时,hpId
的值未定义。您必须将控制台日志放入fetchPatient
订阅中。@Ayaman Safi但在您从HTTP调用中获得它之前,它将是未定义的。它将始终为您提供未定义,因为它将在您的HTTP调用完成之前执行。您的代码很好,如果您尝试在subscribe
中进行控制台操作,您将看到值。将其视为未定义的原因是由于异步行为。是否要在HTML中显示该Id?如果要在模板中显示该Id,请使用|async
管道