简体   繁体   中英

Parse JSON response in Angular 8 with response.json()

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)
          })
      })      
    ) 
}

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)))
  ); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM