Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在angular服务中注入依赖项?_Javascript_Angularjs_Dependency Injection - Fatal编程技术网

Javascript 如何在angular服务中注入依赖项?

Javascript 如何在angular服务中注入依赖项?,javascript,angularjs,dependency-injection,Javascript,Angularjs,Dependency Injection,如果我使用上述格式,即创建一个类定义,然后使用.service符号,声明该服务,我如何使用该服务,例如$http或其他依赖项 这个 在声明服务的位置定义服务时提供解决方案。Angular的注入基于参数名称。如果您将注册模块的名称传递给它,它将找到它并自动注入它 function Greeter(a) { this.greet = function() { //How should I declare the dependency for e.g. $http so that I

如果我使用上述格式,即创建一个类定义,然后使用
.service
符号,声明该服务,我如何使用该服务,例如
$http
或其他依赖项

这个

在声明服务的位置定义服务时提供解决方案。

Angular的注入基于参数名称。如果您将注册模块的名称传递给它,它将找到它并自动注入它

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

请注意,这对于缩小不安全,如果要缩小代码,请改用该语法(并传递数组)。

无论是预先定义类定义还是使用匿名函数,都可以在数组中注释依赖项:

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;
  }
}
或者,您可以使用
$inject
属性:

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

provider.service('greeter', ['a', Greeter]);
您也可以尝试以下方法(这也是缩小安全的):

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

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