angular:HttpClient映射响应 [英] angular: HttpClient map response

查看:85
本文介绍了angular:HttpClient映射响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在从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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆