2016-05-15 112 views
0

我已經看到了很多類似的話題,但我沒有找到解決方案。未知的提供商 - AngularJS

我得到這個錯誤錯誤:

$injector:unpr Unknown Provider

Unknown provider: restaurantsProvider <- restaurants <- restaurantsController

這裏是我的控制器:

(function() { 
    'use strict'; 

    angular 
     .module('myApp') 
     .controller('restaurantsController', restaurantsController); 

    restaurantsController.$inject = ['$scope', 'restaurants']; 

    function restaurantsController($scope, restaurants) { 

     $scope.restaurants = restaurants.query(); 
    } 
})(); 

和服務文件:

(function() { 
    'use strict'; 

    var restaurantsService = angular.module('restaurantsService', ['ngResource']); 

    restaurantsService.factory('restaurantsService', ['$resource', function ($resource) { 
      return $resource('/api/restaurants', {}, { 
       query: { method: 'GET', params: {}, isArray: true } 
      }); 
     }]); 
})(); 

如果它影響到的東西,我m使用ASP.NET。

回答

2

該錯誤表明您正在嘗試注入角度不知道的東西。還有我發現了一些問題與您的應用程序結構,是導致這個問題...

  1. 你從來沒有真正宣告你的「對myApp」模塊,在這裏你需要注入你的restaurantService應用。

  2. 你的控制器需要在「餐廳」的依賴,但該服務實際上是所謂的「restaurantsService」

我希望應用程序的結構看起來是這樣的:

(function() { 
     'use strict'; 

     var restaurantsServiceApp = angular.module('restaurantsServiceApp', ['ngResource']); 

     restaurantsServiceApp.factory('restaurantsService', ['$resource', function ($resource) { 
       return $resource('/api/restaurants', {}, { 
        query: { method: 'GET', params: {}, isArray: true } 
       }); 
      }]); 
    })(); 

(function() { 
    'use strict'; 
    var myApp = angular.module('myApp', ['restaurantsServiceApp']); 
    myApp.controller('restaurantsController', restaurantsController); 

    restaurantsController.$inject = ['$scope', 'restaurantsService']; 

    function restaurantsController($scope, restaurantsService) { 

     $scope.restaurants = restaurantsService.query(); 
    } 
})(); 

你serviceApp需要在被注入其他應用程序之前進行聲明。

+1

這是一個關鍵:「您的服務應用程序需要在被注入其他應用程序之前進行聲明。」在我的app.js中,我忘了添加'restaturantsService'。 _var myApp = angular.module('myApp',['ngRoute',**'restaurantsService'**]); _ –