订阅后服务价值仍未定义
Service values still undefined after subscribing
我有一个函数,一旦用户在表单中选择一个值就会调用它:
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
}
我有一个函数,一旦用户在表单中选择一个值就会调用它:
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
}