TypeError:无法读取未定义的属性"getAccounts"

chr*_*dev 1 javascript dependency-injection iife angularjs

我正在关注John Papa的Angular Style指南来创建一个小应用程序,我似乎无法解决controller使用a service...中的方法的问题.

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

调节器

(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;
            });
        }
    }
})();
Run Code Online (Sandbox Code Playgroud)

服务

(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;
            }
        }
    }
})();
Run Code Online (Sandbox Code Playgroud)

当我运行应用程序时,我得到错误TypeError:无法在控制器中读取未定义的属性'getAccounts',但我无法看到我出错的地方 - 任何帮助都将非常感激.

Mat*_*nis 5

看起来您忘了将accountsDataSvc注入控制器

尝试:

accountsCtrl.$inject = ['$log', 'accountsDataSvc'];
Run Code Online (Sandbox Code Playgroud)