angular - 国家下拉选择后无法读取未定义的属性“订阅”
问题描述
我试图从下拉列表中选择州,在选择国家后我要选择州,即使一切对我来说都很完美,我确实收到了这个错误
core.js:6210 ERROR TypeError: Cannot read property 'subscribe' of undefined
at FormComponent.getStateOnCountrySelection
这是ts文件:
getStateOnCountrySelection(id){
this.selectedStatesOption = [];
this.countriesService.getStates(id).subscribe((data:any) =>{
this.selectedStatesOption.push(data);
});
}
这是选择状态的服务类
public getStates(id: number): Observable<State[]> {
let selectedStates;
this.getCountries().subscribe((data:any) =>{
let states = data["states"];
selectedStates = states.filter((data:any) =>{
return parseInt(data.id) == id
});
});
return selectedStates;
}
请问我做错了什么
解决方案
这里有多个问题
您不会从服务中的函数返回任何内容。
数据是异步获取的。它不能像您尝试的那样同步返回。您需要从函数中返回 observable。您可以使用 RxJS
map
运算符根据要求过滤响应。
服务
public getStates(id: number): Observable<State[]> {
let selectedStates;
return this.getCountries().pipe(
map((data: any[]) => (data['states'].filter(state => parseInt(state.id) == id)) as State[])
);
}
请完整阅读此答案以了解异步数据的工作原理。
推荐阅读
- mysql - kafka jdbc sink 连接器创建无效的数据类型
- python - 使用 pandas 根据指定的频率计算 pct_change
- android - 如何使用 MultiChoiceItems 获取选定的文本,而不是其在 AlertDialog 中的位置
- c# - 我是否在 Quartz.net 中设置了错误的工作?
- python - Python改变变量的引用
- python - 在 Django 中引发异常时,写入日志文件的最佳方法是什么?
- scala - 使用管道分隔符将案例类转换为字符串
- c# - 在调用 SaveChangesAsync() 时,在一对多关系中添加子级会导致异常
- c# - 可以/应该将这三个查询合并为一个吗?
- java - Camera 2 API 问题,图像始终以横向模式显示