gpt4 book ai didi

angular 2命名空间模型

转载 作者:太空狗 更新时间:2023-10-29 17:20:55 24 4
gpt4 key购买 nike

如何在 Angular 2 中使用模型类?

举个例子

模型

namespace model.car {
export class CoolCar {
Id: string;
Name: string;

constructor(){
}
}

export class NiceCar {
Id: string;
Name: string;

constructor(){
}
}
}

namespace model.bike {
export class AwesomeBike {
Id: string;
Name: string;

constructor(){
}
}
}

我想在我的类里面使用它们

var car=new model.car.CoolCar();

但是当我在我的浏览器中运行它时我得到一个错误

"ReferenceError: 'model' is undefined"

我尝试像这样导入模型类

import {CoolCar} from '../model/car/CoolCar'

但是我在 VS2015 中遇到错误:

File "c:/...../model/car/CoolCar.ts is" no module

有人可以帮我吗?

托比亚斯

最佳答案

如果你想公开命名空间,你需要使用关键字export。例如:

// MyModels.ts
export namespace car {
export class NiceCar {
Id: string;
constructor(public name: string) {}
}
}

export namespace bike {
export class AwesomeBike {
Id: string;
constructor(public name: string) { }
}
}

然后将这些命名空间用于:

// main.ts
import * as model from './MyModels';

let car = new model.car.NiceCar('my nice car');
let bike = new model.bike.AwesomeBike('my awesome bike');

console.log(car);
console.log(bike);

请注意,我在 model 命名空间下导入这些类,该命名空间仅在导入时指定,而不是在 MyModels.ts 中指定。

编译为 JS 并运行时将打印到控制台:

$ node main.js 
NiceCar { name: 'my nice car' }
AwesomeBike { name: 'my awesome bike' }

请注意,通常不鼓励在 TypeScript 中使用命名空间。参见 How do I use namespaces with TypeScript external modules?

关于angular 2命名空间模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40201693/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com