![](/img/trans.png)
[英]Angular 5 / Typescript - How to cast complex json object to a class
[英]How to get the proper class during a cast from JSON in typescript?
我的课很简单
export class Foo {
name: string;
index: number;
toFullString(): string {
return `${this.name} | ${this.index}`;
}
}
我从服务器获取此类的元素,并将json转换为此类:
.map(response => response.json() as Foo)
现在发生的事情是,在我调用toFullString()
方法之后,它失败了,因为它不是“真正的” Foo
对象,就像在C#中那样。
那么,实现真正的Foo
对象的正确方法是什么,最好不需要编写自己的构造函数等。
TypeScript中的类型安全有时确实是个笑话。
您可以创建对象并为其提供JSON值。
.map(res => this.onResponse(res))
-
function onResponse(res:any){
this.foo = new Foo();
this.foo.name = res['name'];
...
}
或将JSON值提供给Foo的构造函数
this.foo = new Foo(res['name'], ...);
您要么必须编写自己的构造函数,要么必须使用返回的对象,并使用for(let obj of responseObjects) { obj['toFullString'] = function ... }
附加函数(技术上合法的JS) for(let obj of responseObjects) { obj['toFullString'] = function ... }
。 一个您不想要的,另一个则有点粗略。
您已经看过的构造方法,但我将在这里重复:
constructor(public name, public index) {
this.name = name;
this.index = index;
}
您也可以在地图中进行相同的操作。
masterFoo: Foo = new Foo();
mapFoo(responseObject: any) {
<...>
responseObject['toFullString'] = masterFoo.toFullString;
<...>
}
自动映射仅适用于数据对象,这是一个限制,因为JS是所有对象的基础语言。
这是一个演示如何将函数附加到普通的旧JavaScript对象的插件: http ://plnkr.co/edit/BBOthl0rzjfEq3UjD68I?p=preview
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.