Angular:Typescript 将 JSON 响应转换为对象模型不起作用 [英] Angular: Typescript casting JSON response as object model not working

查看:37
本文介绍了Angular:Typescript 将 JSON 响应转换为对象模型不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试将 json 响应转换为对象时遇到问题,对象的所有属性都是字符串,这正常吗?

I have an issue while I try to cast a json response to object, all the properties of my object are string is that normal ?

这是我的ajax请求:

Here is my ajax request :

public getSingle = (keys: any[]): Observable<Badge> => {
        return this._http.get(this.actionUrl + this.getKeysUrl(keys))
            .map((response: Response) => response.json() as Badge )
            .catch(this.handleError);
}

这是我的徽章模型:

    export interface Badge {
        badgeNumber: number;
        authorizationLevel: number;
        endOfValidity: Date;
    }

这里是我调用服务函数的地方,我遇到了这个问题:

And here is where I call the service function and I'm facing the issue :

this._badgeService.getSingle(this.ids).subscribe(
      (badge: Badge) => {
        console.log(typeof(badge.endOfValidity)); // <-- returning string and not Date
      },
      error => console.log(error);
      });

推荐答案

解释起来有点棘手:

Date 是一个,这意味着需要通过构造函数调用创建 Date 类型的值.换句话说,使用 new Date(...) 创建一个类实例.

Date is a class, this means that values of type Date need to be created through a constructor call. In other words, create a class instance with new Date(...).

Response.json 方法只会返回一个 JSON 格式的对象,并且不包含任何类的实例,只包含 key:property 的映射.

The Response.json method will only return an object in JSON format, and such doesnt contain an instance of any class, only maps of key:property.

所以你需要做的,是手动将 .json() 返回的值转换为 Base 对象.这可以按如下方式完成:

So what you need to do, is to manually convert the value returned from .json() to a Base object. This can be done as follows:

public getSingle = (keys: any[]): Observable<Badge> => {
        return this._http.get(this.actionUrl + this.getKeysUrl(keys))
            .map(r => r.json())
            .map(v => <Badge>{
              badgeNumber: v.badgeNumber,
              authorizationLevel: v.authorizationLevel,
              endOfValidity: new Date(v.endOfValidity)
              // preferably this string should be in ISO-8601 format
             })
            //the mapping step can be done in other ways most likely
            .catch(this.handleError);
}

这篇关于Angular:Typescript 将 JSON 响应转换为对象模型不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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