首页 > 解决方案 > 从可观察的 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 的值超出订阅方法的范围

标签: javascriptangular

解决方案


有两种方法:

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`
}

推荐阅读