Search code examples
jsonangulartypescriptcastingangular2-http

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

Solution

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