且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-16 22:50:20

解释起来有点棘手:

Date 是一个,这意味着需要通过构造函数调用创建 Date 类型的值.换句话说,使用 new Date(...) 创建一个类实例.

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

Response.json 方法只会返回一个 JSON 格式的对象,并且不包含任何类的实例,只包含 key:property 的映射.

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.

所以你需要做的,是手动将 .json() 返回的值转换为 Base 对象.这可以按如下方式完成:

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