我定义了一个生成get请求的工厂,但是当我将它注入控制器时,它总是抛出一个未定义的错误。
这是工厂:
(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
答案 0 :(得分:4)
问题在于您的DI注释。你应该只使用字符串
homeController.$inject = ['homeFactory'];
请参阅https://docs.angularjs.org/guide/di#-inject-property-annotation
$ inject属性是要注入的服务名称的数组。
答案 1 :(得分:1)
控制器功能支持依赖注入。您不需要直接使用$ 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;
}
}
角度运行时将找到homeFactory服务,并在调用时自动将其传递给控制器函数。
答案 2 :(得分:-1)
在控制人员中,您应将工厂置于家属中
app.controller('homeController', ['homeFactory', '$scope',
function (homeFactory, $scope){
//scope code goes here
}]
);