Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I define an AngularJS service using a TypeScript class that doesn't pollute the global scope?
    primarykey
    data
    text
    <p>I am using AngularJS and TypeScript. I want to implement an AngularJS service using a Typescript class, like this:</p> <pre><code>class HelloService { public getWelcomeMessage():String { return "Hello"; } } angular.module('app.services.helloService', []).factory('helloService', () =&gt; { return new HelloService(); }); </code></pre> <p>This compiles to the following javascript code:</p> <pre><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(); }); </code></pre> <p>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?</p> <p>I tried the obvious:</p> <pre><code>angular.module('app.services.helloService', []).factory('helloService', function () { class HelloService { ...} return new HelloService(); }); </code></pre> <p>but that gives me a compile error ("Unexpected token; 'statement' expected.").</p> <p>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.</p> <p>So, my question is, how can I define an AngularJS service using a TypeScript class that doesn't pollute the global scope?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload