我有一个简单的Angular HttpClient,它正确地返回了JSON。我试图强制转换结果以加强类型安全(不确定这是否正确)。
但是,我如何实际访问返回的JSON以将其复制到数组中呢?
httpClient get()请求是(而且看起来运行得很好):
public sendGetRequest(): Observable<Symbols[]> {
return this.httpClient.get<Symbols[]>(this.REST_API_SERVER);
}
Symbols接口是
export interface Symbols {
code: string
desc: string
}
我有一个调用数据服务并得到响应的组件。但是,以下代码在尝试将JSON映射到字符串数组时返回错误
ERROR TypeError: syms.map is not a function
listOfOption: Array<{ value: string; label: string }> = []
this.dataService.sendGetRequest().subscribe((syms: Symbols[]) => {
console.log('return value ' + JSON.stringify(syms))
// console output shows the returned JSON and it looks correct
//this does not work, how do I copy the results to a string array??
this.listOfOption = syms.map(results => {
return {
value: results.code,
label: results.code,
}
})
})
JSON数据结构是:
{
"results": [
{
"code": "code1",
"desc": "Long description of code 1"
},
{
"code": "code2",
"desc": "Long description of code 2"
},
{
"code": "code3",
"desc": "Long description of code 3"
},
{
"code": "code4",
"desc": "Long description of code 4"
}
]
}
这快把我逼疯了
发布于 2020-10-28 14:39:19
对一个名为responseData的新接口建模,以支持响应类型。
export interface responseData{
results: Symbols[]
}
export interface Symbols {
code: string
desc: string
}
在服务中更新相同内容
public sendGetRequest(): Observable<responseData> {
return this.httpClient.get<responseData>(this.REST_API_SERVER);
}
现在可以使用array.map()检索结果。
listOfOption: Array<{ value: string; label: string }> = []
this.dataService.sendGetRequest().subscribe((syms: responseData) => {
console.log('return value ' + syms)
this.listOfOption = syms.results.map(result => {
return {
value: result.code,
label: result.code,
}
})
})
发布于 2020-10-28 13:49:20
响应数据有一个object
根,但您试图将其解析为array
根。我认为最简单的解决方案是这样的:
public sendGetRequest(): Observable<Symbols[]> {
return this.httpClient.get<{results: Symbols[]}>(this.REST_API_SERVER)
.pipe(pluck('results'));
}
它指定响应数据是一个对象,其中包含一个名为results
的字段,该字段包含一个Symbols
数组。
或者,您也可以将响应类型提取到单独的定义中:
interface ApiResponse {
results: Symbols[]
}
public sendGetRequest(): Observable<Symbols[]> {
return this.httpClient.get<ApiResponse>(this.REST_API_SERVER)
.pipe(pluck('results'));
}
https://stackoverflow.com/questions/64567044
复制相似问题