3
function Greeter(a) {
  this.greet = function() {

    //How should I declare the dependency for e.g. $http so that I do a GET request here?
    return 'Hello ' + a;
  }
}


provider.service('greeter', Greeter);

If I am using the above format, where I create a class definition and then using the .service notation, declare the service, how do I use for e.g. $http or other dependencies?

This AngularJS - Dependency injection in services, factories, filters etc

provides a solution when the service is defined where it is declared.

3 Answers 3

2

You can also try this (this is also minification safe):

define([ 'components' ], function() {
  angular.module('components.services').provider('dateFormatService', function() {        
    var self = this;

    self.$get = ['aService', 'bService', function (aService, bService) {
      ...
    }
  });
});
1

Angular's injector injects based on argument name. If you pass the name of a registered module to it it will find it and will inject it automatically.

function Greeter($http) { // the injector will inject $http here
  this.greet = function() {

    //How should I declare the dependency for e.g. $http so that I do a GET request here?
    return 'Hello ' + a;
  }
}

Note that this is not safe for minification, if you intend to minify your code use that syntax instead (and pass an array).

1

It does not matter if you define class definition beforehand or use anonymous function, you can annotate dependencies in array:

function Greeter(b) {
   //provider will inject 'a' service as variable of any name, in this case it's 'b'
}

provider.service('greeter', ['a', Greeter]);

Alternatively, you can use .$inject property:

function Greeter(a) {...}
Greeter.$inject = ['a']; 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.