Search code examples
angularjsglobal-variablestypescriptangularjs-service

How can I define an AngularJS service using a TypeScript class that doesn't pollute the global scope?


I am using AngularJS and TypeScript. I want to implement an AngularJS service using a Typescript class, like this:

class HelloService {
    public getWelcomeMessage():String {
        return "Hello";
    }
}

angular.module('app.services.helloService', []).factory('helloService', () => {
    return new HelloService();
});

This compiles to the following javascript code:

var HelloService = (function () {
    function HelloService() {
    }
    HelloService.prototype.getWelcomeMessage = function () {
        return "Hello";
    };
    return HelloService;
})();

angular.module('app.services.helloService', []).factory('helloService', function () {
    return new HelloService();
});

This pollutes the global namespace with the variable HelloService, which I obviously don't want. (Using Chrome's console I verified that HelloService was an object.) How can I solve/avoid this problem?

I tried the obvious:

angular.module('app.services.helloService', []).factory('helloService', function () {
    class HelloService { ...} 
    return new HelloService();
});

but that gives me a compile error ("Unexpected token; 'statement' expected.").

One possible solution I can think of is using TypeScript's import and export somehow, which in turn will use RequireJS. This probably will wrap the HelloService within a define function, thus avoiding pollution of the global scope with HelloService. However, I don't want to use RequireJS in my AngularJS application for now, as I think AngularJS is good enough for my use, and it adds complexity.

So, my question is, how can I define an AngularJS service using a TypeScript class that doesn't pollute the global scope?


Solution

  • I should provide what I actually ended doing:

    module MyModule {
        export class HelloService {
            public getWelcomeMessage():String {
                return "Hello";
            }
        }
    
        angular.module('app.services.helloService', []).factory('helloService', () => {
            return new HelloService();
        });
    }
    

    In this way I can use

    return new HelloService();
    

    instead of

    return new MyModule.HelloService();