Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

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 ?

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

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);
      });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...