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

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.