Angular: Typescript casting JSON response as object model not working

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

Leave a Comment