angular 2 namespace model
angular, typescript
Solution
You need to use keyword `export` if you want to expose namespaces. For example:
// 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 `model` namespace that is specified only when importing and not in `MyModels.ts`.
This when compiled to JS and run will print to console:
$ 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?
Problem
how can I use model-classes in 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: ``` File "c:/...../model/car/CoolCar.ts is" no module ``` Could anybody help me here? Tobias