当我想通过订阅HTTP请求为Angular组件中的局部变量赋值时 我不确定
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的值超出预订方法的范围
答案 0 :(得分:2)
有两种方法:
1)如果要在HTML页面中显示hdId
,请使用类似{{ 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`
}
答案 1 :(得分:1)