angular:HttpClient映射响应 [英] angular: HttpClient map response
问题描述
当前,我正在从http(@ angular/http)切换到HttpClient(@ angular/common/http),并且在将我的响应映射到对象时遇到了问题.
Currently I'm switching from http (@angular/http) to HttpClient (@angular/common/http) and have problems mapping my response to objects.
旧代码(以前可以工作)
Old code (was working before)
this.http.get(environment.baseUrl + '/api/timeslots')
.map((response: Response) => {
const data = response.json();
const timeslots = Array.of<Timeslot>();
for (const item of data) {...}
新代码,但编译错误:
this.httpClient.get(environment.baseUrl + '/api/timeslots')
.map((response: Response) => {
const data = <Timeslot[]> response;
const timeslots = Array.of<Timeslot>();
for (const item of data) {...}
我想念演员吗?响应是一个时隙数组.
Do I miss a cast? The response is an array of Timeslots.
推荐答案
返回新HttpClient的默认值为Object.它会在内部自动调用response.json()
.
Default value that returns new HttpClient is Object. It automatically calls response.json()
internally.
您可以告诉HttpClient响应将是哪种类型,所以:
You can tell HttpClient what type the response will be, so:
this.httpClient.get<Timeslot[]>(...)
.map((timeSlots) => {
...
其中timeSlots
的类型将为Timeslot[]
在新的HttpClient中查看有关类型检查的更多信息
See more information about typecheking in new HttpClient
这篇关于angular:HttpClient映射响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!