Javascript 同时使用Rxjs映射和过滤器从json中选择国家和州
我有一个包含国家和州的json文件(作为示例): 现在我有了一项服务,可以让国家和州在我的下拉列表中显示:Javascript 同时使用Rxjs映射和过滤器从json中选择国家和州,javascript,json,angular,typescript,rxjs,Javascript,Json,Angular,Typescript,Rxjs,我有一个包含国家和州的json文件(作为示例): 现在我有了一项服务,可以让国家和州在我的下拉列表中显示: export class CountriesService { constructor(private http: HttpClient) { } public getCountries(): Observable<Country[]> { return this.http.get<Country[]>("assets/data.json").
export class CountriesService {
constructor(private http: HttpClient) { }
public getCountries(): Observable<Country[]> {
return this.http.get<Country[]>("assets/data.json").pipe(map(obj => obj["countries"]));
}
public getStates(countryId: number): Observable<State[]> {
return this.http.get<State[]>("assets/data.json").pipe(
map(res => res["states"]),
map(res => { if (res.countryId === countryId) return res;}));
}
}
导出类国家服务{
构造函数(私有http:HttpClient){}
public getCountries():可见{
返回这个.http.get(“assets/data.json”).pipe(map(obj=>obj[“countries”]);
}
public getStates(countryId:number):可观察{
返回这个.http.get(“assets/data.json”).pipe(
映射(res=>res[“状态]),
map(res=>{if(res.countryId===countryId)返回res;});
}
}
getCountries()
按预期工作,只返回Countries
,但我无法从我的getStates
方法中基于countryId
获取特定状态
它什么也不返回
我做错了什么?虽然API调用的结果是一个可观察的,但它“发出”的是一个可观察的,如果是一个由map函数引起的数组,而不是一个可观察的数组。因此,您拥有的第二个映射函数并没有达到预期的效果。相反,在您的第一个映射中,当您获得州时,您可以使用JavaScript数组中名为filter的方法将州向下搜索到具有所需国家id的州
public getStates(countryId: number): Observable<State[]> { return this.http.get<State[]>("assets/data.json").pipe( map(res => res["states"].filter(res => res.countryId === countryId)); }
publicgetstates(countryId:number):可观察的{返回this.http.get(“assets/data.json”).pipe(map(res=>res[“states”].filter(res=>res.countryId==countryId));}
获取数据后,需要对其进行过滤
导出类国家服务{
构造函数(私有http:HttpClient){}
public getCountries():可见{
返回这个.http.get(“assets/data.json”).pipe(
地图(obj=>obj[“国家]),
);
}
public getStates(countryId:number):可观察{
返回这个.http.get(“assets/data.json”).pipe(
映射(res=>res[“状态]),
最晚从(属于(国家ID)),
映射((id,states)=>states.filter(state.countryId==id)),
);
}
}
您还可以将所有数据组合在一起,以避免对不同状态的请求,因为它们仍然是相同的数据
导出类国家服务{
构造函数(私有http:HttpClient){}
public getCountrieswithState():可观察{
返回这个.http.get(“assets/data.json”).pipe(
地图(数据=>data.countries.map)(国家=>({
……国家,
states:data.states.filter(state=>state.countryId===country.id),
}))),
);
}
}
service.getCountriesWithStates().subscribe(国家=>{
//国家[0]。国家[0];
});
我无法合并,因为当有人在下拉列表中选择一个国家时,我需要根据国家获取州。这只是第二个选项。第一个选项单独获取州。这很完美,只需注意countryId是一个整数,所以我将“==”改为“res.countryId==+countryId”即可
public getStates(countryId: number): Observable<State[]> { return this.http.get<State[]>("assets/data.json").pipe( map(res => res["states"].filter(res => res.countryId === countryId)); }