angular.js:14077 TypeError:无法读取属性' getAllContacts'未定义的

时间:2016-09-23 21:36:26

标签: angularjs factory

基本上我有一个工厂可以在两个表(联系人和组织)中提取整个内容 我有这个工厂:

(function () {
    angular.module('appContacts')
        .factory('dataService', ['$q', '$http', dataService]);

    function dataService($q, $http) {

        return {
            getAllContacts: getAllContacts,
            getAllOrganizations: getAllOrganizations
        };

        function getAllContacts() {

            return $http({
                method: 'GET',
                url: 'api/allcontacts',
            })
            .then(sendResponseData)
            .catch(sendGetBooksError)
        }

        function getAllOrganizations() {

            return $http({
                method: 'GET',
                url: 'api/organizations',
            })
            .then(sendResponseData)
            .catch(sendGetBooksError)
        }

        function sendResponseData(response) {
            return response.data;
        }
        function sendGetBooksError(response) {
            return $q.reject('Error retrieving contact(s). (HTTP status: ' + response.status + ')');
        }
    }
})();

我从这个控制器中调用它:

(function () {
    "use strict";
    angular.module('appContacts')
        .controller('contactsController', ['$q', 'dataService', '$http', contactsController]);

    function contactsController($q, $http, $state, dataService) {
            var vm = this;
            vm.allcontacts = [];
            vm.contacts = [];
            vm.organizations = [];
            vm.phones = [];

            // Load all organizations  
             dataService.getAllOrganizations()
                .then(vm.organizations = getAllOrganizations)

            // Load all contacts  
            dataService.getAllContacts()
                .then(vm.allcontacts = getAllContacts);
//more stuff

但我收到错误:      angular.js:14077 TypeError:无法读取属性' getAllContacts'未定义的

任何想法我做错了什么?

1 个答案:

答案 0 :(得分:0)

您的注射不正确。注入的服务和工厂必须对齐(按照引用的顺序注入):

.controller('contactsController',['$q', 'dataService', '$http', contactsController])

function contactsController($q, $http, $state, dataService)

这意味着$q是(正确)'$q'$http'dataService'$state'$http',而dataService未定义。 (您也错过了'$state'注射)

这就是你想要的:

.controller('contactsController',['$q', 'dataService', '$http', '$state', contactsController])

function contactsController($q, dataService, $http, $state)