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);
如果我使用上述格式,我创建类定义然后使用.service
表示法,请声明服务,我如何使用例如$http
或其他依赖项?
此 AngularJS - Dependency injection in services, factories, filters etc
在定义服务时提供解决方案。
答案 0 :(得分:2)
你也可以尝试这个(这也是安全的缩小):
define([ 'components' ], function() {
angular.module('components.services').provider('dateFormatService', function() {
var self = this;
self.$get = ['aService', 'bService', function (aService, bService) {
...
}
});
});
答案 1 :(得分:1)
Angular的injector根据参数名称注入。如果您将已注册模块的名称传递给它,它将找到它并自动注入它。
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;
}
}
请注意,如果您打算缩小代码使用那个语法(并传递数组),这对于缩小是不安全的。
答案 2 :(得分:1)
如果您事先定义类定义或使用匿名函数没关系,您可以在数组中注释依赖项:
function Greeter(b) {
//provider will inject 'a' service as variable of any name, in this case it's 'b'
}
provider.service('greeter', ['a', Greeter]);
或者,您可以使用.$inject
属性:
function Greeter(a) {...}
Greeter.$inject = ['a'];