0

I am building an autocomplete functionality.

1) The backend RESTful service returns following response for partially entered keyword.

JSON response

{
    "suggest": {
    "resultsuggest": [
      {
        "text": "Ke",
        "offset": 0,
        "length": 2,
        "options": [
          {
            "text": "Kevin Johnson",
            "_index": "customernames",
            "_type": "_doc",
            "_id": "1",
            "_score": 3
          }]
      }
  ]
}
}

2) In Angular application, what should I do to extract the options array from the JSON response and return it back for this fetch function?? Note - I want to use the Promise instead of Observable.

fetch(params?: HttpParams): Promise<any> {
        const query = params.get('query');
        const headers = new HttpHeaders().set("Content-Type", "application/json");
        let postData = "{ \"_source\": \"suggest\", \"suggest\": {\"resultsuggest\" : { \"prefix\" : \""+query+"\",\"completion\" : {  \"field\" : \"suggest\",  \"size\" : 5 }}}}";
        return this._http.post<any[]>('http://127.0.0.1:9200/customernames/_search?pretty',postData, {headers})
        .pipe(map(result=> {
                 // what should I do to extract the Options array from the JSON response and return it back in this fetch function??

                 return ????;
           }),
            delay(400)
        ).toPromise();
    }

Appreciate your help!

thanks!

Updated: 1) JSON response is fixed. 2) changed return this._http.post<any> to return this._http.post<any[]>

4
  • Please provide correct JSON. Given one has errors. Commented Nov 3, 2018 at 6:43
  • If my understanding is correct, this will work return JSON.parse(result).suggest.resultsuggest[0].options Commented Nov 3, 2018 at 6:52
  • 1
    No need to A COntent-Type header: HttpClient adds is automatically. No need for JSON.parse(): HttpClient parses automatically. No need to send a JSON string: send a JavaScript object, and HttpCLient sends is as JSON automatically. Read the HttpCLient guide. It's all explained and documented. Commented Nov 3, 2018 at 6:55
  • Thanks! This solved the issue. map(result=> { return result.suggest.resultsuggest[0].options; } Commented Nov 3, 2018 at 7:42

1 Answer 1

0

As Arcteezy suggested, the following worked

map(result=> { return result.suggest.resultsuggest[0].options; }

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.