8

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

Tobias Koller
  • 2,116
  • 4
  • 26
  • 46

2 Answers2

5

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?

Community
  • 1
  • 1
martin
  • 93,354
  • 25
  • 191
  • 226
-1

I think this will help you.

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

Libu Mathew
  • 2,976
  • 23
  • 30