Reputation: 2339
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
Upvotes: 0
Views: 63
Reputation: 668
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
});
}));
}
Upvotes: 0
Reputation: 31125
There are multiple issues here
You aren't returning anything from the function in the service.
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.
Upvotes: 1