【发布时间】:2015-09-17 05:04:04
【问题描述】:
在我能找到的每条信息(包括角度文档)中,将服务注入提供者的方法是通过$get 方法:
var myApp = angular.module('myApp', []);
myApp.provider('helloWorld', function() {
this.$get = function() {
return {
sayHello: function() {
return "Hello, World!"
}
}
};
});
function MyCtrl($scope, helloWorld) {
$scope.hellos = [helloWorld.sayHello()];
}
这将在 angular 1.2 及以下版本中完美运行:http://jsfiddle.net/1kjL3w13/
尽管切换到角度 1.3,$get 函数完全中断。似乎从 $get 函数返回的任何内容都不再用于实例化提供程序,因此现在对于注入 f.e. 没有用。服务。
与上述示例相同,但使用 angular 1.3:http://jsfiddle.net/duefnz47/
这正是 Angular 文档中提供的行为。所以要么文档是错误的,要么我完全误解了它。我真的不在乎 $get 方法是否像以前一样工作,我只需要能够可靠地将服务注入我的提供程序。
【问题讨论】:
-
检查我的回答希望对你有帮助:)。
-
服务、工厂、常量、值等不应该被注入到提供者中...而是在提供者公开的工厂中完成...
-
@deostroll 这是用于构建具有不同目的但可以在两者之间共享方法和内容的提供程序。想想一个“共享”的提供者,其基本功能被注入到许多其他提供者中。你的说法在那种情况下仍然成立吗?另外,需要注入的服务是 f.e. $window 服务,因为我确实需要在我的提供程序中访问它。它确实需要是一个提供者才能在
config方法中注入。 -
这可以通过
angular.injector()完成。但不确定 1.3 支持... -
如果我在我的提供者中直接使用
injector,它会被嘲笑吗?
标签: javascript angularjs dependency-injection angularjs-service angularjs-provider