首页 > 解决方案 > 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

标签: arraysjsonangularextractsubscribe

解决方案


问题是您的流是异步的,因此在分配名称时,肯定从未发出过。

为了解决这个问题,您可以使用第二个地图运算符。这样,您可以根据自己的喜好更改输出,最终值就是您所期望的。

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 即可


推荐阅读