从api调用返回的对象创建类的实例



我正在从一个mongoose api中检索一个Object,我需要将它变成一个自定义类的实例。目前,我已经设置好手动将Object的成员传递到Ingredient类的构造函数中,以创建一个新的Ingredient,如下所示:

ingredient.model.ts:

export class Ingredient {
quantity: number;
unit: string;
description: string;
...
constructor(quantity: number, unit: string, description: string, ...) {
this.quantity = quantity;
this.unit = unit;
this.description = description;
...
}
}

someComponent.component.ts:

import { Ingredient } from "ingredient.model.ts"
foo: Ingredient;
ngOnInit() {
api.getIngredient(id).subscribe((ingredient) => {
this.foo = ingredient;
});
let newIngredient = new Ingredient(foo.quantity, foo.unit, foo.description, ...)
}

我相信有一种更干净的方法可以做到这一点,这样我就可以避免乏味地分配每个成员。我想用一个构造函数来实现这一点;神奇地";将对象转换为Ingredient:的实例

api.getIngredient(id).subscribe((ingredient) => {
let newIngredient = new Ingredient(ingredient);
});

您的型号

export class Ingredient {
quantity: number;
unit: string;
description: string;
constructor(data?) {
data = data || {};
this.quantity = data.quantity;
this.unit = data.unit;
this.description = data.description;
}
}

您的组件

import { Ingredient } from "ingredient.model.ts"
foo: Ingredient;
ngOnInit() {
this.foo = new Ingredient({});
api.getIngredient(id).subscribe((ingredient) => {
this.foo = new Ingredient(ingredient);
});
let newIngredient = new Ingredient(this.foo)
}

为什么不使用接口并且getIngredient返回Observable<Ingredient>

示例:

配料界面

export interface Ingredient {
quantity: number;
unit: string;
description: string;
...
}

API服务

public getIngredient(id: string | yourType): Observable<Ingredient> {
.... 
return httpService.get<Ingredient>(...);
}

组件

api.getIngredient(id).subscribe((ingredient) = this.foo = ingredient);

通过这种方式,您告诉getIngredient的响应是一个Ingredient接口,您不需要分配属性。

当然,只有当您在Ingredient中没有任何方法时,这才是有效的,否则您必须切换到class,但逻辑是相同的

最新更新