Angularjs工厂注入错误

Angularjs factory inject error

本文关键字:错误 注入 工厂 Angularjs      更新时间:2023-09-26

我使用angularJS,当我注入一个工厂时,我得到错误:

app.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

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

您多次创建模块:

angular.module('myapp', [])

你应该做一次。然后在没有[]的情况下使用

angular.module('myapp').factory ...
angular.module('myapp').controller ...

错误的原因是在创建httpServicecontroller时,您使用了setter,即angular.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() {
}
});

以下是文档的链接

是,

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

你需要做的是定义它一次,然后继续使用这个实例

var app = angular.module('myapp', []);
app.factory('httpService', function($http, $timeout) {
});
app.controller('test',  function($scope, $timeout, $sce, $http, httpService) {
  $scope.submit = function() {
  }
});

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

代码应该如下所示:

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