【问题标题】:Unknown Provider - AngularJS未知提供者 - AngularJS
【发布时间】:2016-05-15 23:17:07
【问题描述】:

我看过很多这样的话题,但我没有找到解决方案。

我收到此错误错误:

$injector:unpr 未知提供者

未知提供者:restaurantProvider

这是我的控制器:

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

如果它影响某些东西,我使用的是 ASP.NET。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    该错误表明您正在尝试注入 Angular 不知道的东西。我发现您的应用结构存在一些导致此问题的问题...

    1. 你从来没有真正声明你的“myApp”模块,这是你需要注入你的餐厅服务应用程序的地方。

    2. 您的控制器接受“餐厅”依赖项,但该服务实际上称为“餐厅服务”

    我希望应用程序结构看起来像这样:

        (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 需要在注入其他应用程序之前声明。

    【讨论】:

    • 这是一个关键:“您的 serviceApp 需要在注入其他应用程序之前声明。”在我的 app.js 中,我忘记添加“restaturantsService”。 var myApp = angular.module('myApp', ['ngRoute', 'restaurantsService']);
    猜你喜欢
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多