如何使用Angularjs将依赖项注入提供程序?

Chu*_*ung 33 angularjs

是否可以在提供者方法中进行DI?

在这个例子中

angular.module('greet',[])
.provider('greeter',function() {

  this.$get=function() {

  };
})
.service('greeterService',function($http){
  console.log($http);
})
;
Run Code Online (Sandbox Code Playgroud)

注入$http服务似乎是正确的实现,但它在提供程序方法中不起作用并且它会引发错误:

未知提供商:$ http

提供者方法是否与DI一起注入服务?

Buu*_*yen 58

你当然可以注入$http提供者.只要确保它出现在$get,而不是函数构造函数.如下:

angular.module('greet',[]).provider('greeter',function() {
  this.$get = function($http) {

  };
});
Run Code Online (Sandbox Code Playgroud)

  • 提供者文档有一个缩小安全示例(https://docs.angularjs.org/guide/providers).`this.$ get = ["apiToken",函数unicornLauncherFactory(apiToken){return new UnicornLauncher(apiToken); }];` (14认同)
  • WTF当天的一刻对我来说:) (3认同)

z0r*_*z0r 13

您可以将常量和其他提供程序注入提供程序.不是服务或工厂 - 有一个例外.您似乎可以将$injector服务注入提供程序 - 至少,您可以在AngularJS 1.3.16中.

.provider('foo', ['$injector', function ($injector) {
  var messagePrefix = $injector.get('msgPrefix');
  this.message = '';

  this.$get = function() {
    var that = this;
    return function() {
      return messagePrefix + that.message;
    }
  };
}])
Run Code Online (Sandbox Code Playgroud)

您可以在$get方法外使用注入器,但在配置时仍然无法从中获取服务.

请参阅此处获取演示.


Dun*_*unc 6

跟进IgrCndd的回答,这是一种可能避免潜在危险的模式:

angular.module('greet',[]).provider('greeter', function() {

    var $http;

    function logIt() {
        console.log($http);
    }

    this.$get = ['$http', function(_$http_) {
        $http = _$http_;

        return {
            logIt: logIt
        };
    }];
});
Run Code Online (Sandbox Code Playgroud)

注意这与同等服务有多相似,使得两者之间的转换不那么麻烦:

angular.module('greet',[]).factory('greeter', ['$http', function($http) {

    function logIt() {
        console.log($http);
    }

    return {
        logIt: logIt
    };
});
Run Code Online (Sandbox Code Playgroud)