我有一个简单的TypeScript类,定义如下:
export class Piece {
Qty: number;
Weight: number;
Type: string;
totalWeight() {
return Qty * Weight;
}
}
而且,我有一个Angular 5服务,它具有如下方法:
get(id: number) {
return this.http.get<Piece>(myAPIURL + id);
}
我的Angular代码将其调用如下:
const myPiece: Piece;
this.myService.get(2).subscribe(data => myPiece = data);
说完之后,变量“ myPiece”包含正确的数据;但是,没有附加totalWeight()方法。我想我理解为什么(因为服务器返回了数据/属性,但显然没有代码)。但是,有什么方法可以再次将数据和代码/方法结合起来吗?
我的背景是C#对象,但对Java / TypeScript还是很陌生。我猜想这可能与JavaScript中的原型继承有关?
有什么帮助吗?
您实际上需要从http调用实例化该类。TypeScript只是具有类型提示的javascript,不能进行实际的转换,因为javascript没有此功能。因此,要使某类成为某个类,您确实必须使用new
关键字实例化该类
get(id: number) {
return this.http.get<Piece>(myAPIURL + id).pipe(
map((data) => ({ ...new Piece(), ...data}))
)
}
要么
map((data) => Object.assign(new Piece(), data))
无论您觉得更清晰
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句