繁体   English   中英

使用 response.json() 在 Angular 8 中解析 JSON 响应

[英]Parse JSON response in Angular 8 with response.json()

我正在尝试从 angular 8 的 API 获取搜索数据。我的方法response.json()有问题,因为它创建了一个错误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)
          })
      })      
    ) 
}

使用Angular HttpClient 时,您的请求会自动解析为 JSON(除非请求的响应类型未设置为处理不同的数据类型)。 正如@Alexander Statoselsky 在评论中所说,您可以设置响应的类型,因此 TypeScript 现在将从后端返回什么数据结构。

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

此外,在使用 queryParameters 时,您可能需要查看您将用作以下示例的HttpParams

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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