我遇到了臭名昭著的未知提供商错误,并研究了这里的每个潜在答案,但我认为我遗漏了一些东西:
app.js
var myApp = angular.module('myApp', [
'ngResource',
'myAppControllers',
'myAppServices',
'myAppFilters'
]).config([
'$locationProvider',
function(
$locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false,
rewriteLinks: false
});
}]);
var myAppControllers = angular.module('myAppControllers', []);
var myAppServices = angular.module('myAppServices', []);
var myAppFilters = angular.module('myAppFilters', []);
Item.js
myAppServices.factory('Item',
function($resource) {
return $resource('/api/items/:id');
});
ItemService.js (1)
myAppServices.factory('itemService',
function($q,
$http,
Item) {
return {
delete: function(id){
// Item, $q and $http are undefined here
return Item.delete({id: id}).$promise;
}
};
});
替代ItemService.js (2)
myAppServices.factory('itemService', [
'$q',
'$http',
'Item', // If I don't inject it here I can use this service with $q and $http
function($q,
$http,
Item) {
return {
delete: function(id){
return Item.delete(id).$promise;
}
};
}]);
在我的 Controller 中:
myAppControllers.controller('ItemsCtrl', [
'$scope',
'itemService',
function(
$scope,
itemService) {
var ctrl = this;
ctrl.ItemService = ItemService;
ctrl.deleteItem = function(id){
ctrl.itemService.delete(id)
.then(function(response){
console.log(response);
}, function (error) {
console.log(error);
});
};
}]);
因此,如果我像 (1) 那样尝试,则会得到 undefined。delete 不是
itemService
中的函数。 .如果我按照 (2) 进行尝试,应用程序将无法加载:
Unknown provider: ItemProvider <- Item <- itemService
那我做错了什么?
最佳答案
您遇到了多个问题。
您需要将
myAppServices
作为myAppControllers
的依赖项才能在 Controller 中使用它。因此,您应该这样做:
var myAppServices = angular.module('myAppServices', []); var myAppControllers = angular.module('myAppControllers', ['myAppServices']);
- 在
myAppServices
模块中,您有Item
服务,该服务使用$resource
但您尚未注入(inject)ngResource
作为myAppServices
的依赖项。
这是您的code in plunker没有错误
编辑:还要确保您的所有文件都正确包含在 index.html
中!
关于javascript - AngularJS $resource 中的未知提供者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43778924/