Search code examples
javascriptangularjsangular-resourceangular-factory

Unknown Provider in AngularJS $resource


I am getting the infamous unknown provider error, and looked into every potential answer up here but I think that I am missing something:

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

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

And in my 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. So if I try like in (1), I am getting undefined.delete is not a function in itemService.

  2. If I try as in (2), the app fails to load with:

    Unknown provider: ItemProvider <- Item <- itemService

So what am I doing wrong?


Solution

  • You have multiple issues here.

    • You need to have myAppServices as a dependency of myAppControllers in order to use it in a controller.

      So, following should be how you do it:

      var myAppServices = angular.module('myAppServices', []);
      var myAppControllers = angular.module('myAppControllers', ['myAppServices']);
      
    • In myAppServices module you have Item service which uses $resource but you haven't injected ngResource as a dependency of myAppServices.

    Here's your code in plunker without errors

    EDIT: Also make sure all your files are included in index.html properly!