Search code examples
angularjstypescriptangularjs-service

Best practice for dependency injection in an AngularJS service with TypeScript


I find dependency injection for AngularJS services in TypeScript to be somewhat cumbersome. Currently, I define a factory method inside my service class, and have to repeat all dependency injection arguments three times:

class MyService {
    public static Factory($rootScope, myController) {       // 1st time
        return new MyService($rootScope, myController);     // 2nd time
    }
    constructor(public $rootScope, public myController) {}  // 3rd time
}
myModule.factory('myService', MyService.Factory);

I would like to do the following, but that does not seem to work:

class MyService {
    constructor(public $rootScope, public myController) {}  // only once
}
myModule.factory('myService', MyService);

This approach works fine for controllers, but not so for services. Is there a better way?

Thanks in advance!


Solution

  • You could simply use angular's injector to create your controller instead of having a factory method.

    Here is a sample in typescript

    /// <reference path='d.ts/DefinitelyTyped/angularjs/angular.d.ts' />
    
    class MyCtrl {
      public phrase: string;
      constructor($window) {
        this.phrase = 'I was loaded by injector';
      }
    
      speak() {
        alert(this.phrase);
      }
    }
    
    function main() {
      var injector = angular.injector(['ng']);
      var ctrl = injector.instantiate(MyCtrl);
      ctrl.speak();
    }
    

    And a fiddler to prove it works: http://jsfiddle.net/UPv5j/3/