【问题标题】:angular 2 namespace modelangular 2 命名空间模型
【发布时间】:2017-03-05 05:50:42
【问题描述】:

如何在 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

有人可以帮我吗?

托比亚斯

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    如果你想公开命名空间,你需要使用关键字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?

    【讨论】:

      【解决方案2】:

      我想这会对你有所帮助。

      cars.ts

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

      coolcar.ts

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

      Typescript Reference

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-10
        • 2011-08-16
        • 1970-01-01
        • 2017-03-21
        • 1970-01-01
        • 2012-07-08
        • 2012-04-18
        • 2011-05-23
        相关资源
        最近更新 更多