typescript angular 2 命名空间模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40201693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:57:08  来源:igfitidea点击:

angular 2 namespace model

angulartypescript

提问by Tobias Koller

how can I use model-classes in angular 2?

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

here is an example

这是一个例子

Model

模型

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(){
        }
    }
}

I would like to use them in my classes like

我想在我的课程中使用它们

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

but when I run this in my browser I get an error

但是当我在浏览器中运行它时出现错误

"ReferenceError: 'model' is undefined"

I tried to Import the model-classes like

我试图导入模型类

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

but then I get an error in VS2015:

但随后我在 VS2015 中收到错误消息:

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

Could anybody help me here?

有人可以帮我吗?

Tobias

托比亚斯

采纳答案by martin

You need to use keyword exportif you want to expose namespaces. For example:

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) { }
    }
}

Then use these namespaces with:

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

// 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);

Note I'm importing these classes under modelnamespace that is specified only when importing and not in MyModels.ts.

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

This when compiled to JS and run will print to console:

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

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

Note that it's generally discouraged to use namespaces in TypeScript. See How do I use namespaces with TypeScript external modules?

请注意,通常不鼓励在 TypeScript 中使用命名空间。请参阅如何将命名空间与 TypeScript 外部模块一起使用?

回答by Libu Mathew

I think this will help you.

我想这会对你有所帮助。

cars.ts

汽车.ts

export namespace Cars {
    export class CoolCar { /* ... */ }
    export class NiceCar { /* ... */ }
}

coolcar.ts

酷车.ts

import * as car from "./cars";
let c = new cars.Cars.CoolCar();

Typescript Reference

打字稿参考