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)
          })
      })      
    ) 
}
Dawid Zbiński
  • 5,521
  • 8
  • 43
  • 70
Jocelyn
  • 13
  • 1
  • 3

1 Answers1

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)))
  ); 
}
Dawid Zbiński
  • 5,521
  • 8
  • 43
  • 70