angular - 订阅后服务值仍未定义
问题描述
我有一个函数,一旦用户在表单中选择一个值,就会调用它:
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
. 有什么建议么?
解决方案
以下是订阅的工作方式:
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
}
推荐阅读
- javascript - Angular HTTP客户端如何知道分块下载请求何时完成?
- java - 如何从 JTable 中获取选定的行并将其设置为 JTextArea?
- python - 循环遍历目录时代码不起作用:TypeError:__array_function__ 的调度程序没有返回可迭代
- javascript - 反应项目的构建版本没有正确重定向站点
- plotly-dash - Dash/Plotly - 使用 multi true 时如何关闭下拉列表中的清除值?
- python - 不能在苹果硅上使用 conda/miniforge
- python - 在没有 IFrame 的 Selenium 中单击侧面板元素
- qt - 如何在 Qt 的状态机中实现选择?
- jquery - 查找具有名称属性的输入不起作用 - jquery
- python - 将表单信息添加到 SQLite 数据库 python