I have an issue in AngularJS. I am trying to authenticate the user and when a response got back from the server I use a service to store the user state as he is admin or not. Till now everything is fine but when I navigate from one route to the other, the service loses its data and become undefined. Any idea how to solve that?
here is the service:
angular.module("AccApp")
.service('Session', function(){
this.create = function (userName, userRole) {
this.userName = userName;
this.userRole = userRole;
};
this.destroy = function () {
this.userName = null;
this.userRole = null;
};
return this;
});
here is the authentication service which set the session service:
angular.module("AccApp")
.factory('AuthService',['$http','$cookieStore','Session','$q', function($http, $cookieStore, Session, $q){
var authService = {};
var AuthentoctionControllerUrl = "http://localhost:18678/api/Authentication/";
authService.login = function(credentials) {
var deferred = $q.defer();
return $http.post(AuthentoctionControllerUrl, credentials).success(function(response){
$cookieStore.put('AuthorizationHeader', response.Token);
Session.create(response.Name, response.IsAdmin);
deferred.resolve(response);
}).error(function(error){
deferred.reject(error);
});
return deferred.promise;
};
authService.logout = function () {
$cookieStore.remove('AuthorizationHeader');
};
authService.isAuthenticated = function () {
if(Session.userName) return true;
else return false;
};
authService.isAuthorized = function (authorizedRole) {
if(authService.isAuthenticated() && authorizedRole <= Session.userRole) return true;
else return false;
};
return authService;
}]);
her is the log in controller.
angular.module("AccApp")
.controller('LoginController',['$scope','AuthService','$location', function($scope, AuthService, $location){
$scope.credentials = {
EmailAddress: '',
password: ''
};
$scope.Login = function () {
AuthService.login($scope.credentials).then(function(response){
$location.path('/temp1');
},
function(error){
alert("still need work");
});
};
}]);
if you want to store data while navigating between pages you can use the following code:
add it to service.js
.service('sharedProperties', function () {
var property = null;
return {
getModel: function () {
return property;
},
setModel: function(value) {
property = value;
}
}
})