Javascript 从observeble HTTP请求的订阅为角度分量中的变量赋值

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

当我想通过订阅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.patientService.getPatient(id)
    .subscribe( data => {
      this.patient = data;
      this.hpId = this.patient.appointment[0].healthProfessionalId;
    });
  }
}
我想使用订阅方法范围之外的hpId值
  • 用typescript编码就像管道一样..你必须像 流动如果你打开水龙头,但如果水在路上,直到它到达 水龙头里没有水,所以如果你打算洗衣服,你就得洗 水从水龙头里出来之后
  • 因此,当您调用此方法时。fetchPatient(id);它将击中目标 后端并在订阅中等待,直到它获取数据或出错。之后 这个病人的身份证;然后将console.log(this.hpId)放入; 此时未检索到数据,但因此进行了调用 它将显示未定义的。如果要查看数据,请将其放入控制台日志 在该行this.hpId之后进行内部订阅= 此.patient.appointment[0].HealthProfessional ID
  • 此外,如果要在其他方法中使用this.hpId的值
    在此之后调用这些方法。hpId=
    此.patient.appointment[0].HealthProfessional ID;线路
  • 有两种方法:

    1) 如果要在HTML页面中显示
    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
    管道