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