首页 > 解决方案 > 国家下拉选择后无法读取未定义的属性“订阅”

问题描述

我试图从下拉列表中选择州,在选择国家后我要选择州,即使一切对我来说都很完美,我确实收到了这个错误

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;
  }

请问我做错了什么

标签: angularrxjs

解决方案


这里有多个问题

  1. 您不会从服务中的函数返回任何内容。

  2. 数据是异步获取的。它不能像您尝试的那样同步返回。您需要从函数中返回 observable。您可以使用 RxJSmap运算符根据要求过滤响应。

服务

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[])
  );
}

请完整阅读此答案以了解异步数据的工作原理。


推荐阅读