我知道这是一个非常基本的问题。我有一个文件
dinosaur.model.ts
,我在其中定义了一个接口,我还想定义一个模板
export interface Dinosaur {
height: number;
weight: number;
lifespan: number;
diet: string;
// and 70 other features
在同一个文件中,我希望能够实例化恐龙类型的对象,并将其导出
export class customDefaults {
herbivoreTemplate: Dinosaur = {
height: 21;
weight: 6.7;
lifespan: 65;
// 71 other features
}
carnivoreTemplate: Dinosaur = {
height: 8;
weight: 1.7;
lifespan: 52;
// 71 other features
}
我需要做的是将模板的特定实例导入到组件中,我知道这应该非常简单,但我无法使其工作。在
my-component.ts
我正在尝试:
constructor(
initialHerbivore: Dinosaur,
) {
initialHerbivore = new customDefaults().herbivoreTemplate;
我也尝试过
export class herbivoreTemplate {
height: number = 21;
weight: number = 65;
// etc.
constructor(@Inject(Object) obj: Dinosaur) {
Object.assign(this, obj);
}
}
但无论我尝试什么,总是会出现错误,而且我总是在原地打转。模板很长,我需要经常调用它们,我认为使用类型的接口,并在
dinosaur.model.ts
文件中创建对象实例是最好的方法。我不想为此使用服务,因为我已经在后台运行了大量服务。
您可以简单地将实例导出到
customDefaults
文件中,而不是创建 dinosaur.model.ts
类:
export const herbivoreTemplate: Dinosaur = {
height: 21;
weight: 6.7;
lifespan: 65;
// 71 other features
}
然后您可以像
import { herbivoreTemplate } from 'dinosaur.model.ts'
一样导入它并像任何其他变量一样使用它。
请注意,
const
关键字仅禁止重新分配,但由于您正在处理全局变量,因此无法保证模板中的值不会被修改。 (这个问题也存在于你的方法中)