【发布时间】:2021-07-12 12:29:03
【问题描述】:
我正在尝试从带有 angular 的 json 响应服务中提取 firstname 字段并返回一个包含名字的数组。
这是 json 对象:
{
"hits": {
"hits": [
{
"_id": "BKZujHgB0urOc7uDCrf5",
"_index": "names",
"_score": 1.0,
"_source": {
"firstname": "Alicia"
},
"_type": "_doc"
},
{
"_id": "BaZujHgB0urOc7uDL7e2",
"_index": "names",
"_score": 1.0,
"_source": {
"firstname": "Alice"
},
"_type": "_doc"
}
]
}
我创建了一个服务来使用返回 json 对象而不使用 observables 的 web 服务。 appService.ts
public autoComplete(name: string) {
const params = new HttpParams()
.set('name', name);
return this.httpClient.get(this.host, { params});
在 app.component.ts 中,我创建了一个调用该服务的函数并在 ngOnInit() 中实现了它,我遵循了自动完成角度材料并稍作修改。但我总是遇到 Cannot read property 'hits' of undefined
的错误ngOnInit() {
this.seachText.valueChanges.pipe(
startWith(''),
// delay emits
debounceTime(300),
// use switch map so as to cancel previous subscribed events, before creating new once
map(value => this.lookup(value))
).subscribe(value => this.results$ = value);
this.names = this.results$.hits.hits.map(h => h._source.firstname);
console.log('resultat :', this.names);
}
我不知道如何纠正错误,但我想我从服务中提取的 json 对象中提取数据的方式有误
【问题讨论】:
-
您需要在回调内部进行。阅读规范的stackoverflow.com/q/14220321/3001761
标签: arrays json angular extract subscribe