dacox
dacox

Reputation: 502

TypeScript and AngularJS - Module is undefined?

I have been writing a rather large AngularJS app of directives in TypeScript according to the following article: http://kwilson.me.uk/blog/writing-cleaner-angularjs-with-typescript-and-controlleras/.

I have organized my Controllers and Directives into subfolers of my appm Controllers, and Directives.

My main.ts looks like so:

module Test {
    angular.module("myModule", ["myDep"])
           .controller(Test.Controllers)
           .directive(Test.Directives);
    }
}

my _all.ts looks like so

/// <reference path='Controllers/x.ts' />
/// <reference path='Directives/x.ts' />
/// <reference path='Controllers/y.ts' />
/// <reference path='Directives/y.ts' />
/// <reference path='Test/main.ts' />

Everything has been working great, until I attempted to add a service.

I took some duplicated functions between the controllers x and y and put them in a service, under the folder Services

module Test.Services {
    export class TestService {

        test(): string {
            return "test";
        }
    }
}

added it to my _all.ts

/// <reference path='Controllers/x.ts' />
/// <reference path='Directives/x.ts' />
/// <reference path='Controllers/y.ts' />
/// <reference path='Directives/y.ts' />
/// <reference path='Services/test.ts' />
/// <reference path='Test/main.ts' />

and attempted to add it to my app:

module Test {
    angular.module("myModule", ["myDep"])
           .controller(Test.Controllers)
           .directive(Test.Directives)
           .service("testService", Test.Services.TestService);
    }
}

I can get everything to compile, and IntelliSense seems to accept it, but when I render my page, I get

Uncaught TypeError: Cannot read property 'TestService' of undefined

It doesn't seem to see my Test.Services module, and I can't figure out why. It is clearly compiling, I can see the Services in the transpiled JavaScript.

If I attempt to do a

console.log(Test.Services);

in main.ts, I get undefined, but not for Controllers or Directives

If I move my service into the same module Test that angular.module gets called in, it works - but only if it is in the same lexical scope as the angular.module call. If I keep it in the same separate file, but in the Test module, it doesn't work.

I am very confused here.

Upvotes: 0

Views: 550

Answers (1)

basarat
basarat

Reputation: 276393

I am very confused here

This is the hazard of using out. See lots of reasons why you shouldn't : https://github.com/TypeStrong/atom-typescript/blob/master/docs/out.md

Temp fix:

Reorder the files in _all.ts so that the variables are declared in the order they are used

Long term fix:

Use commonjs everywhere and for the frontend have something like webpack running.

Upvotes: 2

Related Questions