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
The namespace is used for logical grouping of functionalities. A namespace can include interfaces, classes, functions and variables to support a single or a group of related functionalities. A namespace can be created using the namespace keyword followed by the namespace name.
While namespaces are not deprecated, using namespaces as the code organization mechanism in your code base is not always recommended.
Namespaces are simply named JavaScript objects in the global namespace. This makes namespaces a very simple construct to use. Unlike modules, they can span multiple files, and can be concatenated using outFile .
The export as namespace form creates a global variable so it can be used without importing, but you may still import it with the import { name } from "some-library" form of import.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With