我有以下代码:
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不是函数 初始化时(http://localhost:9000/scripts/controllers/login.js:78:53) 在新的LoginCtrlr(http://localhost:9000/scripts/controllers/login.js:22:9) at - var sessionService = ServiceFactory.getLoginSession();
答案 0 :(得分:2)
您的工厂服务似乎没有公开cotroller或其他服务将使用的所有公共方法;恩。 setUserSession,getLoginSession等我也看到了其他问题,但错误未定义不是函数,因为你没有将这些方法暴露给外界。
为此,您的服务必须遵循以下模式:
(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
};
}
})();