【问题标题】:Service values still undefined after subscribing订阅后服务值仍未定义
【发布时间】:2021-07-03 07:35:41
【问题描述】:

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

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。有什么建议吗?

【问题讨论】:

  • 这是一个异步调用。您必须将日志移到订阅中才能工作。
  • 你确定$x.target.value返回的是真实的选择值吗?
  • @Random 很好,但我将它保存到变量中,值不应该留在那里吗?如果没有,那我该如何使用这个变量呢?
  • @Moamen 是的,参数在那里并且正确。
  • 当您收到来自 HTTP 调用的应答时执行订阅。因此,在设置变量时做某事的唯一方法是在订阅中进行(或在订阅中调用方法)。订阅之外的任何内容都不能保证在 HTTP 调用响应后执行

标签: angular service components


【解决方案1】:

以下是订阅的工作方式:

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
}

【讨论】:

  • 非常感谢,这非常有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-25
  • 1970-01-01
  • 2021-05-16
  • 2020-11-21
  • 1970-01-01
  • 2018-07-18
  • 1970-01-01
相关资源
最近更新 更多