javascript - 从可观察的 HTTP 请求的订阅中为角度组件中的变量赋值
问题描述
当我想通过订阅 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 的值超出订阅方法的范围
解决方案
有两种方法:
1)如果您想hdId
在 HTML 页面中显示,请使用 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`
}
推荐阅读
- oneget - 新的 winget 和 Microsoft.PackageManagement 有什么关系
- symfony - Symfony 5:如何使用 OneToMany 关系向会话中经过身份验证的用户添加数据?
- css - div元素在设置宽度为0后不折叠?
- java - 如何从 Android 上的 firebase 获取标记的信息?
- javascript - 如何将 Converse js XMPP 与 React 应用程序集成
- java - 如何根据文本文件中的特定关键字解析文本文件
- ruby-on-rails - 为测试目的创建一个完全载入的条带连接帐户?
- c - Linux Socket - 重定向 stdout/stderr 后读取返回 0
- xcode - 显示相互依赖数据数组的最佳 Xcode/cocoa 方法
- javascript - 如何将 JS 承诺转换为另一个对象