AngularJS $resource 中的未知提供商

Unknown Provider in AngularJS $resource

我遇到了臭名昭著的未知提供者错误,并查看了这里的每一个可能的答案,但我认为我遗漏了一些东西:

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;
            }
        };
    }]);

在我的控制器中:

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. 所以如果我像 (1) 那样尝试,我会得到 undefined.delete 不是 itemService 中的函数。

  2. 如果我尝试 (2),应用程序无法加载:

    Unknown provider: ItemProvider <- Item <- itemService

那我做错了什么?

这里有多个问题。

  • 您需要 myAppServices 作为 myAppControllers 的依赖项才能在控制器中使用它。

    因此,您应该按照以下方式操作:

    var myAppServices = angular.module('myAppServices', []);
    var myAppControllers = angular.module('myAppControllers', ['myAppServices']);
    
  • myAppServices 模块中你有 Item 服务使用 $resource 但你没有注入 ngResource 作为 myAppServices 的依赖项。

这是您的 code in plunker,没有错误

编辑:还要确保所有文件都正确包含在 index.html 中!

我认为你在 $resource 中缺少参数它应该看起来像

$resource('/api/items/:id', {id:'@id'});

再试试(1),未定义是因为这个

而且你的删除应该是这样的

return Item.delete({id : id}).$promise;