我定义了一个发出 get 请求的工厂,但是当我将它注入(inject) Controller 时,它总是抛出一个未定义的错误。
这是工厂:
(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;
}
})();
这是 Controller :
(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'];
参见 https://docs.angularjs.org/guide/di#-inject-property-annotation
The $inject property is an array of service names to inject.
关于javascript - AngularJS - 我不明白为什么工厂总是未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34192861/