[英]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.