Javascript AngularJS-I don';我不明白为什么工厂总是没有定义
我定义了一个发出get请求的工厂,但当我将它注入控制器时,它总是抛出一个未定义的错误 这是工厂:Javascript AngularJS-I don';我不明白为什么工厂总是没有定义,javascript,angularjs,web,Javascript,Angularjs,Web,我定义了一个发出get请求的工厂,但当我将它注入控制器时,它总是抛出一个未定义的错误 这是工厂: (function() { 'use strict'; var app = angular .module('myApp'); app.factory('homeFactory', homeFactory); function homeFactory ($q, $http, $location) { var data = {};
(function() {
'use strict';
var app = angular
.module('myApp');
app.factory('homeFactory', homeFactory);
function homeFactory ($q, $http, $location) {
var data = {};
data.getProducts = getProducts;
function getProducts() {
return $http.get('http://localhost:8000/api/v1/products')
.error(errorMessage);
}
function errorMessage(response) {
console.log('There was an error', response);
}
return data;
}
})();
这是控制器:
(function() {
'use strict';
var app = angular
.module('myApp');
app.controller('homeController', homeController);
homeController.$inject =[homeFactory];
function homeController(homeFactory) {
var home = this;
homeFactory.getProducts()
.success(success);
function success(jsonData, statusCode) {
console.log('The request was successful', statusCode);
console.dir(jsonData);
home.products = jsonData;
}
}
})();
看起来还可以,但控制台会抛出:
Uncaught ReferenceError: homeFactory is not defined
问题出在DI注释中。您应该只使用字符串
homeController.$inject = ['homeFactory'];
看
$inject属性是要注入的服务名称的数组
问题出在DI注释中。您应该只使用字符串
homeController.$inject = ['homeFactory'];
看
$inject属性是要注入的服务名称的数组
在控制器中,应将工厂置于从属状态
app.controller('homeController', ['homeFactory', '$scope',
function (homeFactory, $scope){
//scope code goes here
}]
);
在控制器中,应将工厂置于从属状态
app.controller('homeController', ['homeFactory', '$scope',
function (homeFactory, $scope){
//scope code goes here
}]
);
控制器函数支持依赖项注入。您不需要直接使用$injector。试试这个:
var app = angular
.module('myApp');
app.controller('homeController', homeController);
function homeController(homeFactory) {
var home = this;
homeFactory.getProducts()
.success(success);
function success(jsonData, statusCode) {
console.log('The request was successful', statusCode);
console.dir(jsonData);
home.products = jsonData;
}
}
angular运行时将找到homeFactory服务,并在调用时自动将其传递给控制器函数。控制器函数支持依赖项注入。您不需要直接使用$injector。试试这个:
var app = angular
.module('myApp');
app.controller('homeController', homeController);
function homeController(homeFactory) {
var home = this;
homeFactory.getProducts()
.success(success);
function success(jsonData, statusCode) {
console.log('The request was successful', statusCode);
console.dir(jsonData);
home.products = jsonData;
}
}
angular运行时将找到homeFactory服务,并在调用该服务时自动将其传递给控制器函数。如果错误发生在控制器中,您可能应该显示该代码(以及完整的实际错误消息)。使用未缩小版本的
angular.js
获取更详细的错误消息如果错误发生在控制器中,您可能应该显示该代码(以及完整的实际错误消息)。使用未缩小版本的angular.js
获取更详细的错误消息海报使用的是$inject
而不是数组注入。此外,如果不使用$scope
,则无需注入。海报使用的是$inject
,而不是数组注入。另外,如果您不使用它,就不需要注入$scope
。虽然这可能在开发中起作用,但如果这些脚本为生产而缩小,这将中断。实际上,建议使用$inject
,以避免缩小问题。然而,正如另一个答案所建议的,$inject
需要一个字符串,这就是问题所在。虽然这可能在开发中起作用,但如果这些脚本被缩小以用于生产,这将中断。实际上,建议使用$inject
,以避免缩小问题。然而,正如另一个答案所建议的,$inject
需要一个字符串,这就是问题所在。