简体   繁体   English

Angular:Typescript将JSON响应转换为对象模型不起作用

[英]Angular: Typescript casting JSON response as object model not working

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 ? 我在尝试将json响应投射到对象时遇到问题,我的对象的所有属性都是字符串,是否正常?

Here is my ajax request : 这是我的ajax请求:

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);
}

Here is my badge model : 这是我的徽章模型:

    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);
      });

Thats kinda tricky to explain: 很难解释:

Date is a class , this means that values of type Date need to be created through a constructor call. Date是一个 ,这意味着需要通过构造函数调用来创建Date类型的值。 In other words, create a class instance with new Date(...) . 换句话说,使用new Date(...)创建一个类实例。

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. Response.json方法将仅返回JSON格式的对象,并且该类不包含任何类的实例,仅包含key:property的映射。

So what you need to do, is to manually convert the value returned from .json() to a Base object. 因此,您需要做的是将.json()返回的值手动转换为Base对象。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM