【发布时间】:2021-01-25 05:50:37
【问题描述】:
在我使用这种方法之前,我正在练习从一个包含国家和州列表的 json 文件中读取数据,但是我想使用 httpClient 并且通过测试我有这些方法,但是正确的方法是什么读取此数据。 早期方法:
getCountries(): Observable<Country[]> {
return of(countries['countries']);
}
getStates(countryID): Observable<State[]> {
return of(countries['states'].filter(f => f.countryId === countryID));
}
这是我的工作方式:
getC(): Observable<Country[]> {
return this.http.get<Country[]>(this.link).pipe(map(k => {
return k['countries'];
}));
}
getS(CID): Observable<State[]> {
return this.http.get<State[]>(this.link).pipe(map(v => {
return v['states'].filter(f => f.countryId === CID);
}));
}
我看到这样的东西,但我有错误
getC3(): Observable<Country[]> {
return this.http.get<Country[]>(this.link)
.toPromise()
.then(res => <Country[]>res.countries)
.then(data => {return data});
}
这样做的正确方法是什么, 错误:
几天过去了,看来问题很严重,所以问这边,从这个json获取数据的方法是什么:
[
{
"data": [
{
"label": "Select State",
"value": null
},
{
"label": "Adeje",
"value": {
"county": "Gran Canaria",
"state": "Islas Canarias",
"country": "España"
}
},
{
"label": "Agaete",
"value": {
"county": "Gran Canaria",
"state": "Islas Canarias",
"country": "España"
}
}
]
}
]
以及如何从这个 json 中获取数据:
[
{
"label": "Select State",
"value": null
},
{
"label": "Adeje",
"value": {
"county": "Gran Canaria",
"state": "Islas Canarias",
"country": "España"
}
},
{
"label": "Agaete",
"value": {
"county": "Gran Canaria",
"state": "Islas Canarias",
"country": "España"
}
}
]
考虑到我使用--strict模式
【问题讨论】:
-
你得到什么错误(以及在哪里)?
-
我修改我的问题
-
这能回答你的问题吗? Angular 5 Service to read local .json file
-
否,因为在这个例子中使用了
我想使用类名 -
嗯,我不确定正确的类型是什么...我从未将类型附加到
.get()
标签: json angular typescript