【发布时间】: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