简体   繁体   中英

How to inject dependencies in angular services?

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 eg $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.

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) {
      ...
    }
  });
});

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).

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']; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM