Angular: Typescript casting JSON response as object model not working

前端 未结 1 378
栀梦
栀梦 2020-12-02 01:18

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 ?

Here is my ajax request :



        
相关标签:
1条回答
  • 2020-12-02 02:08

    Thats kinda tricky to explain:

    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(...).

    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.

    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);
    }
    
    0 讨论(0)
提交回复
热议问题