arrays - extract data from service with angular
问题描述
I am trying to extract firstname fields from a json response service with angular and return an array full of firstnames.
this the the json object :
{
"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"
}
]
}
i have created a service to consume the webservice that returns the json object without using observables. appService.ts
public autoComplete(name: string) {
const params = new HttpParams()
.set('name', name);
return this.httpClient.get(this.host, { params});
and in the app.component.ts I Have created a function that calls the service and implemented it in ngOnInit() ,i have followed the autocomplete angular material with a little modification . but i am always having errors of 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);
}
i dont know how to correct the error but i guess that i am wrong with the way that i am using to extract the data from the json object comming from the service
解决方案
问题是您的流是异步的,因此在分配名称时,肯定从未发出过。
为了解决这个问题,您可以使用第二个地图运算符。这样,您可以根据自己的喜好更改输出,最终值就是您所期望的。
this.searchText.valueChanges
.pipe(
startWith(""),
debounceTime(300),
map(value => this.appService.autoComplete(value)),
map(results => results.hits.hits.map(hit => hit._source.firstname))
)
.subscribe(value => (this.results = value));
在 StackOverflow 上查看此复制:https ://stackblitz.com/edit/stackoverflow-67142850
如果您希望您的autoComplete方法返回一个 observable,只需在使用时将map替换为switchMap 即可。
推荐阅读
- html - 如何修复 tailwindcss-cli 抛出 TypeError: Object.fromEntries is not a function?
- bash - 如何重命名文件并从一个 s3 存储桶移动到另一个
- c - getchar() 在将字符存储在结构变量的成员中时不会自行执行
- xcode - Xcode 警告我“malloc”的隐式声明,但 stdlib.h 包含在标头中
- python - 使用python链接图像中的破损边缘
- flutter - Dart Isolate 作为永久工人
- javascript - 扩展运算符以更新对象数组
- css - 在 CSS 媒体查询中放置一个 id
- reactjs - 反应警报重复 2 次
- reactjs - PropType.shape({}) 失败警告:无效类型