7

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!

2 Answers 2

6

You should user service not factory :

class MyService {
    constructor(public $rootScope) {}  // only once
}
myModule.service('myService', MyService);
Sign up to request clarification or add additional context in comments.

1 Comment

Also note that 'myModule.service('myService', MyService);' must go after class declaration. Placing it before will make code compiling but causing errors in runtime (something like accessing prototype on undefined).
1

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/

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.