0

我正在使用angularJS,当我注入工厂时出现错误:

应用程序.js:

angular.module('myapp', [])

myfactory.js:

angular.module('myapp', [])
.factory('httpService', function($http, $timeout) {

});

控制器:test.js:

angular.module('myapp', [])
.controller('test',  function($scope, $timeout, $sce, $http, httpService) {

  $scope.submit = function() {
  }
});

当我添加httpService我得到错误。一切似乎都是正确的,我什至在所有项目中都使用了这个工厂。错误:

angular.min.js:92 Error: [$injector:unpr] http://errors.angularjs.org/1.2.25/$injector/unpr?p0=httpServiceProvider%20%3C-%20httpService
at Error (native)
at http://localhost:81/chah/assets/js/angularjs/angular.min.js:6:450
at http://localhost:81/chah/assets/js/angularjs/angular.min.js:36:202
at Object.c [as get] (http://localhost:81/chah/assets/js/angularjs/angular.min.js:34:305)
at http://localhost:81/chah/assets/js/angularjs/angular.min.js:36:270
at c (http://localhost:81/chah/assets/js/angularjs/angular.min.js:34:305)
at d (http://localhost:81/chah/assets/js/angularjs/angular.min.js:35:6)
at Object.instantiate (http://localhost:81/chah/assets/js/angularjs/angular.min.js:35:165)
at http://localhost:81/chah/assets/js/angularjs/angular.min.js:67:419
at http://localhost:81/chah/assets/js/angularjs/angular.min.js:54:25
4

4 回答 4

6

检查错误中的链接(https://docs.angularjs.org/error/$injector/unpr?p0=httpServiceProvider%20%3C-%20httpService):

您多次创建模块:

angular.module('myapp', [])

你应该做一次。然后使用不带 []

angular.module('myapp').factory ...
angular.module('myapp').controller ...
于 2016-05-19T09:05:17.167 回答
3

错误的原因是因为在创建httpServiceand thecontroller时您使用了setterieangular.module('myapp', [])语法module而不是getter 语法。angular.module('myapp'). Angular 要求我们只定义一个模块一次,因此随后的重新定义会导致错误。

所以在 中app.js,定义module

angular.module('myapp', []) ;

myfactory.js使用 getter 语法时,删除, []

angular.module('myapp')
.factory('httpService', function($http, $timeout) {
});

并在test.js

angular.module('myapp')
.controller('test',  function($scope, $timeout, $sce, $http,  httpService) {

$scope.submit = function() {
}
});

这是文档的链接

于 2016-05-19T09:08:19.130 回答
1

是的,

你正在做的是重新创建你的应用程序

您需要做的是定义一次并继续使用该实例

var app = angular.module('myapp', []);

app.factory('httpService', function($http, $timeout) {

});

app.controller('test',  function($scope, $timeout, $sce, $http, httpService) {

  $scope.submit = function() {
  }
});

或者如果你想检索你的应用程序,语法是 angular.module('myapp') 这将返回 'myapp',但是添加 [],告诉 angular 创建一个应用程序而不是获取它

于 2016-05-19T09:03:21.387 回答
0

代码应如下所示:

angular.module('myapp', [])
.factory('httpService', function($http, $timeout) {

});
.controller('test',  function($scope, $timeout, $sce, $http, httpService) {

  $scope.submit = function() {
  }
});
于 2016-05-19T10:43:57.160 回答