0

I am attempting to select state from a drop down, after selecting the country and I am to select the state, I do get this error even though everything looks perfect to me

core.js:6210 ERROR TypeError: Cannot read property 'subscribe' of undefined
    at FormComponent.getStateOnCountrySelection

Here is the ts file:

getStateOnCountrySelection(id){
    this.selectedStatesOption = [];
    this.countriesService.getStates(id).subscribe((data:any) =>{
      this.selectedStatesOption.push(data);
    });
  }

Here is the service class class to pick the states

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

Please what am I doing wrong

ruth
  • 29,535
  • 4
  • 30
  • 57
Blaze
  • 2,269
  • 11
  • 40
  • 82

2 Answers2

1

There are multiple issues here

  1. You aren't returning anything from the function in the service.

  2. The data is obtained asynchronously. It cannot be returned synchronously like you're attempting to. You need to return the observable from the function instead. You could use RxJS map operator to filter the response as per the requirement.

Service

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

Please read this answer in it's entirety to know how async data works.

ruth
  • 29,535
  • 4
  • 30
  • 57
0

You are retuning an array not an observable.

This is an approximate function. Maybe have issues.

public getStates(id: number): Observable<State[]> {

    return this.getCountries().pipe(map((data:any) =>{
      
      let states = data["states"];
      return  states.filter((data:any) =>{
        return parseInt(data.id) == id
      });
    }));
  }
dmance
  • 628
  • 1
  • 8
  • 26