如何将http请求响应映射到TypeScript中定义的对象 [英] How do I map http request response to my defined object in TypeScript

查看:221
本文介绍了如何将http请求响应映射到TypeScript中定义的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始了解Angular,TypeScript和RxJS.我有一个返回JSON的http请求.在此JSON中,有一些数据需要构造我定义的对象.假设我的对象是这样的:

I'm getting to know Angular, TypeScript and RxJS. I have an http request that returns a JSON. In this JSON there is data that I need to construct my defined object. Let's say, that my object is this:

export class RegularUser {
    constructor(
        public id: number,
        public firstName: string,
        public lastName: string,
        public token: string
    ) {}
}

现在,我正在向某个API发送请求,该API会以以下格式返回数据:

Now, I am sending a request to some API, which returns data in this format:

{
    success: boolean,
    uid: number,
    first_name: string,
    last_name: string,
    cid: number,
    rights: number[]
    token: string
}

我有HttpClient服务,所以我想这样做:

I have the HttpClient service, so I thought I would do:

this.httpClient.get(
    'http://api.example.com/api/get_user'
).pipe(
    tap((receivedData: Response) => console.log(receivedData)),
    map((receivedData: Response) => {
        return new RegularUser(
            receivedData.uid, 
            receivedData.first_name, 
            receivedData.last_name, 
            receivedData.token);
    })
);

但是对于TypeScript, receivedData 对象没有上面列出的参数.我是否必须为API响应创建一个接口,然后将其映射到我的 RegularUser 对象?

But for TypeScript, the receivedData object doesn't have above-listed params. Do I have to create an interface for the API response and then map it to my RegularUser object?

推荐答案

您可以指定

You can specify a type for get() such as an interface. Why an intermediary/additional interface may be warranted for separation of concerns in your situtation is that get() with a type will not new up an instance of class RegularUser. An intermediary/additional interface can be created with properties you expect from the server response that will be used to create an instance of your end class:

interface Foo {
  uid: number,
  first_name: string,
  last_name: string,
  token: string
}

this.httpClient.get<Foo>(
    'http://api.example.com/api/get_user'
).pipe(
    tap((receivedData: Foo) => console.log(receivedData)),
    map((receivedData: Foo) => {
        return new RegularUser(
            receivedData.uid, 
            receivedData.first_name, 
            receivedData.last_name, 
            receivedData.token);
    })
);

如果您不需要新建类 RegularUser 的实际实例,将其作为具有属性的接口或类就足够了:

If you do not need to new up an actual instance of class RegularUser, it may be enough it to just have it as an interface or class with properties:

this.httpClient.get<RegularUser>(
    'http://api.example.com/api/get_user'
).pipe(
    tap((receivedData: RegularUser) => console.log(receivedData))
);

希望有帮助!

这篇关于如何将http请求响应映射到TypeScript中定义的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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