javascript - AngularJS $resource 中的未知提供者

标签 javascript angularjs angular-resource angular-factory

我遇到了臭名昭著的未知提供商错误,并研究了这里的每个潜在答案,但我认为我遗漏了一些东西:

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

  2. 如果我按照 (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/

相关文章:

javascript - 需要有关 Angular Factory 的帮助

angularjs - 动态资源头

iFrame 中的 JavaScript 修改 iFrame 之外的对象

angularjs - 更改资源的基本 URL

javascript - 如何存储刷新 token ?

javascript - 如何为可编辑日期设置正确的日期格式

javascript - Angular JS - 范围观察不更新

angularjs - 使用 firebase 托管 nodeJS 应用程序

javascript - 用其他语言编写 JavaScript

javascript - 自定义元素双向绑定(bind)更新不触发valueChange