【问题标题】:Unable to connect with Service functions in angularjs无法连接angularjs中的服务功能
【发布时间】:2016-05-06 13:14:05
【问题描述】:

我有以下代码:

Service:

(function () {
    'use strict';

    angular
        .module('myApp')
        .factory('ServiceFactory', ServiceFactory);

    ServiceFactory.$inject = ['$http', '$rootScope', 'serviceURLHostFactory','$q'];

    var config = {
        // TO DO : check if anything required
    };

    /* @ngInject */
    function ServiceFactory($http, $rootScope, serviceURLHostFactory, $q) {

        
        var session = {};
        var userName = null;
        var userId = null;
        var pwd = null;
       
        

        function getUserSession() {
            return session;
        }

        function setUserSession(session) {
            session = session;
        }

        function getUserName() {
            return userName;
        }

        function setUserName(userName) {
            userName = userName;
        }

        function getUserId() {
            return userId;
        }

        function setUserId(userId) {
            userId = userId;
        }

        function getPwd() {
            return pwd;
        }

        function setPwd(pwd) {
            pwd = pwd;
        }

       
        var service = {
            getUserSession: getUserSession,
            setUserSession: setUserSession,
            getUserName: getUserName,
            setUserName: setUserName,
            getUserId: getUserId,
            setUserId: getUserId,
            getPwd:getPwd,
            setPwd:setPwd,
            getLoginSession: getLoginSession
        };

		var response ={};
        //Fetch Use Session
        function getLoginSession() {
            var URL = serviceURLHostFactory.getServiceServerHost();

            /*return $http({
                        method: 'POST', 
                        url: 'response.json', 
                        data: {'username': getUserName, 'pwd': getPwd}
                    })
                .then(httpCompleted)
                .catch(httpFailed);*/
            response = user":{"uid":"3","name":"xyz","mail":"test23@localhost.com","theme":"","signature":"","signature_format":"filtered_html","created":"1462429963","access":"1462445668","login":1462445753,"status":"1","timezone":"Asia/Kolkata","language":"","picture":null,"data":false,"roles":{"2":"authenticated user"},"rdf_mapping":{"rdftype":["sioc:UserAccount"],"name":{"predicates":["foaf:name"]},"homepage":{"predicates":["foaf:page"],"type":"rel"}}}}
            return response;

            function httpCompleted(response) {
                return response.data;
            }

            function httpFailed(e) {
                console.error('Unable to Login' + JSON.stringify(e));
                return $q.reject(e);
            }
        }



        return response;
    }
})();

Ctrlr:

(function () {
  'use strict';

angular
    .module('myApp')
    .controller('LoginCtrlr', LoginCtrlr);

LoginCtrlr.$inject = ['$scope','$cookieStore','ServiceFactory','$timeout', '$q', '$document', '$rootScope', '$window'];

/* @ngInject */
function LoginCtrlr($scope, $cookieStore, ServiceFactory, $timeout, $q, $document, $rootScope, $window) {


    var vm = this;

    vm.errMessageLogin = '';
    var errMessageLogin = {}; // error message json object
    var errMessageArrayLogin = []; // error message  array
    var constErrMessageLogin = "Please select a Resort from the drop down list.";
    //vm.setErrorMessage = setErrorMessage;

    initialize();


    function setProcessingParameters(message) {
        vm.messageTxt = message;
        vm.processingUrl = '/login.html';
    }

    function openProgressBar() {
        var defer = $q.defer();
        vm.globalPromise = defer.promise;
        return defer;
    }

    function initialize() {
        var defer = $q.defer();
        var deferTimer = $q.defer();

        $timeout(function () {
            if (defer !== null) {
                //vm.setProcessingParameters('No Message');
                //defer = vm.openProgressBar();
                deferTimer.resolve();
            }
        }, 1000);

        deferTimer.promise.then(function () {
            $timeout(function () {
                if (defer !== null) {
                    defer.resolve();
                    //vm.setProcessingParameters('Please Wait...');
                    //defer = vm.openProgressBar();
                }

            }, 4000);
        });

        vm.loggedInUserId = $cookieStore.get('userId') || null;
        console.log("getSession..");
        $cookieStore.remove('userId');

        if (vm.loggedInUserId !== '') {
            vm.loggedInUserId = vm.loggedInUserId;
        } else {
            vm.loggedInUserId = '';
        }
        console.log('Login Name in bank in UI controller : ' + vm.loggedInUserId);
        if (vm.loginInUserId === undefined) {
            vm.loginInUserId = '';
        }

        if (vm.loggedInUserId !== undefined && vm.loggedInUserId !== '' && vm.loggedInUserId !== null) {
            console.log("User exists..logged in");
        }
        else {

            var sessionService = ServiceFactory.getLoginSession();
            sessionService
                .then(onAuthenticated )
                .catch(onRejectedRequest)
                .finally(sessionServiceFinally);

        }

        function onAuthenticated(resposne) {
            console.log('User Session :'+ resposne.data);

            $cookieStore.put('userId', resposne.data.userId);
            //Set the suer session here and in session name, id etc can be set in factory
            ServiceFactory.setUserSession(resposne.data);

             vm.deferPromise.promise.then(closeProgressBar);
        }

        function onRejectedRequest(e) {
            console.error('Error in Response of Events List :: ' + JSON.stringify(e.data));
            if (e.status === 401 || e.status === 403) {
                var logoutURL = $window.location.protocol + '//' + $window.location.host + '/ui/logout.html';
                $window.location.assign(logoutURL);
            } else {
                if (e.status === 500 || e.status === 404) {
                    alert(e.data.code + ':' + e.data.message);
                } else {
                    alert(e.data.errMsg);
                }
            }
        }

        function sessionServiceFinally() {
            defer.resolve();
            defer = null;
        }

        function closeProgressBar() {
            defer.resolve();
            defer = null;
        }
    }
}
})();

在这里,我试图在登录时存储用户会话。它抛出以下错误:

TypeError: undefined is not a function 在初始化 (http://localhost:9000/scripts/controllers/login.js:78:53) 在新的 LoginCtrlr (http://localhost:9000/scripts/controllers/login.js:22:9) at - var sessionService = ServiceFactory.getLoginSession();

【问题讨论】:

    标签: javascript angularjs undefined


    【解决方案1】:

    您的工厂服务似乎没有公开所有将被控制器或其他服务使用的公共方法;前任。 setUserSession、getLoginSession 等。我看到还有其他问题,但错误 undefined is not a function 是因为您没有将方法暴露给外界。

    为此,您的服务必须遵循以下模式:

        (function () {
        'use strict';
    
        angular
            .module('myApp')
            .factory('ServiceFactory', ServiceFactory);
    
        ServiceFactory.$inject = ['$http', '$rootScope', 'serviceURLHostFactory','$q'];
    
        var config = {
            // TO DO : check if anything required
        };
    
        /* @ngInject */
        function ServiceFactory($http, $rootScope, serviceURLHostFactory, $q) {
    
    
            var session = {};
            var userName = null;
            var userId = null;
            var pwd = null;
    
    
    
            function getUserSession() {
                return session;
            }
    
            function setUserSession(session) {
                session = session;
            }
    
            function getUserName() {
                return userName;
            }
    
            function setUserName(userName) {
                userName = userName;
            }
    
            function getUserId() {
                return userId;
            }
    
            function setUserId(userId) {
                userId = userId;
            }
    
            function getPwd() {
                return pwd;
            }
    
            function setPwd(pwd) {
                pwd = pwd;
            }
    
    
            return {
                getUserSession: getUserSession,
                setUserSession: setUserSession,
                getUserName: getUserName,
                setUserName: setUserName,
                getUserId: getUserId,
                setUserId: getUserId,
                getPwd:getPwd,
                setPwd:setPwd,
                getLoginSession: getLoginSession
            };
    
        }
    })();
    

    【讨论】:

    • 你能指导我解决其他问题吗@rout
    猜你喜欢
    • 2014-12-20
    • 2019-02-07
    • 2018-11-11
    • 2020-11-29
    • 2016-07-24
    • 2022-06-22
    • 1970-01-01
    • 2014-02-14
    • 2020-04-06
    相关资源
    最近更新 更多