[英]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
.我正在尝试从 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)
})
})
)
}
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).使用Angular HttpClient 时,您的请求会自动解析为 JSON(除非请求的响应类型未设置为处理不同的数据类型)。 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.
正如@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)))
);
}
Also, when using queryParameters, you might want to take a look at HttpParams which you'd use as following example此外,在使用 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.