首页 > 解决方案 > 订阅后服务值仍未定义

问题描述

我有一个函数,一旦用户在表单中选择一个值,就会调用它:

onChange($x: any){
  this.ApiService
      .getCarsByManufacturer($x.target.value)
      .subscribe(data => this.carListAfterManufacturerSelect = data);
  console.log(this.carListAfterManufacturerSelect)
}

服务:

getCarsByManufacturer(manufacturer: string): Observable<Cars[]>{
    return this.http.get<Cars[]>(this.apiBaseUrl + '/cars/spec/' + manufacturer)
  }

我想使用用户选择的值作为我的函数的参数,但carListAfterManufacturerSelect一直返回undefined. 有什么建议么?

标签: angularservicecomponents

解决方案


以下是订阅的工作方式:

onChange($x: any){
  this.ApiService.getCarsByManufacturer($x.target.value).subscribe(data => {
    this.carListAfterManufacturerSelect = data;
    console.log('2. Received !', this.carListAfterManufacturerSelect); // filled
    this.codeToBeExecutedAfterHttpCallIsReceived()
  });
  console.log('1. Not received yet', this.carListAfterManufacturerSelect); // undefined
}

codeToBeExecutedAfterHttpCallIsReceived() {
  console.log('3. Received too !', this.carListAfterManufacturerSelect); // filled
  // do a lot of complex stuff with carListAfterManufacturerSelect
}

推荐阅读