1

I am trying to get the search data from an API in angular 8. I have a problem with method response.json() as it creates an error response.json is not a function.

search(query: string): Observable<SResult[]> {   
  const queryUrl = `${url}${params}`;
  return this.http.get(queryUrl, {headers})   
    .pipe(
      map((response : any) => {
        return (<any>response.json())
          .map((res) => {
            return new SearchResult(res)
          })
      })      
    ) 
}
3
  • Hi, you can reffer to the link for your problem : stackoverflow.com/questions/46630893/… Commented Feb 20, 2020 at 16:05
  • please edit your question to be clear Commented Feb 20, 2020 at 16:05
  • 1
    HttpClient automatically parses the response as JSON you do not need to add response.json(). Instead just make it a typed response Commented Feb 20, 2020 at 16:11

1 Answer 1

1

When using angular HttpClient your request is automatically parsed as JSON (unless the request's response type is not set to handle different data type). As @Alexander Statoselsky said in the comment, you can set the type of your response, so TypeScript will now what data structure is returned from the backend.

search(query: string): Observable<SearchResult[]> {   
  const queryUrl = `${url}${params}`;
  return this.http.get<CustomResultInterface[]>(queryUrl, {headers}).pipe(

    // As HttpClient cares only about the structure, you still need to loop 
    // through the returned data and create a classes if you want the method to return
    // a list of SearchResult classes.
    // CustomResultInterface is your custom interface that carries only the structure of the response
    map(results => results.map(result => new SearchResult(result)))
  ); 
}

Also, when using queryParameters, you might want to take a look at HttpParams which you'd use as following example

search(query: string): Observable<SearchResult[]> {   
  const params = new HttpParams();
  params.set('query', query);
  return this.http.get<CustomResultInterface[]>(url, { params, headers }).pipe(
    map(results => results.map(result => new SearchResult(result)))
  ); 
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Dawid Zbiński. Now I have the follow TypeError: results.map is not a function.
Well, then the results are not an array. Try console logging it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.