【发布时间】:2016-09-24 03:55:49
【问题描述】:
我有一个使用 Angular 开发的简单应用程序。我尽可能简化了以下内容。我正在尝试制作globally available library injectible(没什么特别的):
我的app.module.js文件简单定义为:
angular.module('dogApplication', [
'dogModule',
'dogSelection'
]);
index.html 文件定义如下(为便于阅读而删减):
<html lang="en" ng-app="dogApplication">
<head>
<!-- ... -->
<script src="app/app.module.js"></script>
<script src="app/dogs/dog.module.js"</script>
<script src="app/dogs/dog.factory.js"</script>
<script src="app/dogSelection.module.js"></script>
<!-- controllers then imported -->
</head>
<body>
<!-- content -->
</body>
</html>
.module 文件定义了每个其他组件、控制器、工厂等附加到的模块,app.module.js 是“主”模块附件。
dog.factory.js定义如下:
angular
.module('dogModule')
.factory('dog', function($window) {
// do logic defined by James Hill in linked article
return friendly;
});
然后我有一个控制器:
angular
.module('dogSelection')
.controller('dogSelectionController', ['$scope', 'dog', function ($scope, dog) {
if (dog)
{
console.log('it worked');
}
}])
访问应用程序时,我收到一条我无法完全解决的糟糕错误消息:
angular.js:13920 Error: [$injector:unpr] Unknown provider: dogProvider <- dog <- dogSelectionController
http://errors.angularjs.org/1.5.8/$injector/unpr?p0=dogProvider%20%3C-%20dog%20%3C-%20dogSelectionController
at angular.js:68
at angular.js:4511
at Object.getService [as get] (angular.js:4664)
at angular.js:4516
at getService (angular.js:4664)
at injectionArgs (angular.js:4688)
at Object.invoke (angular.js:4710)
at $controllerInit (angular.js:10354)
at nodeLinkFn (angular.js:9263)
at angular.js:9673
按照我上面的设置方式,为什么dog 服务不能通过 DI 提供给dogSelectionController?
我知道.factory( //... 方法中的代码可以工作,因为我可以将它附加到控制器定义的末尾;但是,我希望工厂在整个应用程序中都可用。这可能吗?
【问题讨论】:
-
您在注入数组上将其定义为
leaflet,但在实际参数中定义为dog。我相信他们需要匹配才能工作。 -
@Lex 他们不需要匹配。唯一的限制是字符串中的名称必须与它来自的任何模块中的服务的实际名称匹配
-
@Lex 这是一个帖子错误,抱歉。我需要解决这个问题。试图使其更广泛地适用。
-
服务在整个应用程序之间共享,它们属于哪个模块无关紧要。正如已经说过的那样,代码还有其他问题,这些问题没有解释发生了什么,但暗示了某些事情已经搞砸了。使用非子模块中的单元是一种不好的做法。如果 'dogSelection' 依赖于 'dogModule' 单元(
dog服务),它应该直接声明其依赖关系,angular.module( 'dogSelection', ['dogModule'])。 -
@Lex 我同意你 100% 同意这个肯定会导致一些问题的订单
标签: javascript html angularjs