TypeError: Cannot read property 'getAccounts' of undefined

TypeError: Cannot read property 'getAccounts' of undefined

我正在遵循 John Papa 的 Angular 创建小型应用程序的风格指南,但我似乎无法使用 [=14] 中的方法解决 controller 的问题=]...

模块

(function () {
    'use strict';
    var accountsApp = angular.module('accountsApp', ['ui.bootstrap', 'ngAnimate']);
})();

控制器

(function() {
    'use strict';

    angular
        .module('accountsApp')
        .controller('accountsCtrl', accountsCtrl);

    accountsCtrl.$inject = ['$log'];

    function accountsCtrl($log, accountsDataSvc) {
        /* jshint validthis:true */
        var vm = this;
        vm.title = 'Accounts';
        vm.accounts = [];
        vm.accountForm = null;
        vm.account = { id: 0, name: '', description: '' }

        activate();

        function activate() {
            return getAccounts(1).then(function() {
                $log.info('Accounts loaded');
            });
        }

        function getAccounts(id) {
            return accountsDataSvc.getAccounts(id).then(function(data) { //error here
                vm.accounts = data;
                return vm.accounts;
            });
        }
    }
})();

服务

(function () {
    'use strict';

    angular
        .module('accountsApp')
        .factory('accountsDataSvc', accountsDataSvc);

    accountsDataSvc.$inject = ['$http', '$log'];

    function accountsDataSvc($http, $log, $q) {

        var uri = '***';

        var service = {
            getAccounts: accounts
        };

        return service;

        //////////////////////

        function accounts(userId) {
            $log.info(uri + userId + ' called');
            return $http.get(uri + userId)
                .then(getAccountsComplete)
                .catch(function (message) {
                    $log.error('XHR Failed for getAccounts ' + message);
                });

            function getAccountsComplete(data, status, headers, config) {
                return data.data[0].data.results;
            }
        }
    }
})();

当我 运行 应用程序时,我收到错误 TypeError: Cannot read 属性 'getAccounts' of undefined within the controller,但是我看不出哪里出了问题 - 任何帮助将不胜感激。

您似乎忘记将 accountsDataSvc 注入控制器

尝试:

accountsCtrl.$inject = ['$log', 'accountsDataSvc'];