我是angularjs的新手,通过在登录页面中使用jsonwebtokens生成的令牌进行身份验证。在验证后,它会重定向到主页。当我刷新页面时,清除所有变量都不显示任何内容。 以下代码用于具有身份验证的登录功能。
app.factory("authenticationSvc", ["$http","$q","$window","$location","$rootScope", function ($http, $q, $window,$location,$rootScope) {
var userInfo;
$rootScope.loggedIn == false;
function login (uName, uPwd)
{
var deferred = $q.defer();
$http({
method: "POST",
url: "/api/login",
data: {
uName : uName,
pwd : uPwd
}
}).then(function(result)
{
if (result.data.access_token != null)
{
userInfo = {
resToken : result.data.access_token,
resuName : result.data.uName,
resfName : result.data.fName,
reslName : result.data.lName
};
$window.sessionStorage["userInfo"] = JSON.stringify(userInfo);
deferred.resolve(userInfo);
}
else if (result.data.access_token == null)
{
var userErr = {
resErr : result.data.err,
resuName : result.data.uName
};
console.log("This is userErr "+ userErr.resErr + " " + userErr.resuName);
deferred.resolve(userErr);
}
},function (error) {
deferred.reject(error);
}
);
return deferred.promise;
}
function logout()
{
var deferred = $q.defer();
$http({
method: "POST",
url: "/api/logout",
headers: {
"access_token": userInfo.resToken
}
}).then(function (result) {
userInfo = null;
$window.sessionStorage["userInfo"] = null;
deferred.resolve(result);
}, function (error) {
console.log("Error is also at factory");
deferred.reject(error);
});
return deferred.promise;
}
function getUserInfo()
{
return userInfo;
}
function init()
{
if ($window.sessionStorage["userInfo"])
{
console.log("init function executes");
userInfo = JSON.parse($window.sessionStorage["userInfo"]);
console.log("init function userInfo"+ userInfo);
}
}
init();
return {
login : login,
getUserInfo: getUserInfo
};
}]);
//authenticationSvc factory Ends Here
//Signin Controllers
app.controller('signinCtrl',function($scope,$location,$rootScope,$window,authenticationSvc)
{
$scope.login = function ()
{
authenticationSvc.login($scope.uName,$scope.uPwd)
.then(function (result)
{
if (result.resToken != null)
{
$rootScope.loggedIn = true;
// $scope.userInfo = result;
$rootScope.user = result.resfName +" " + result.reslName;
$location.path('/home');
}else if (result.resToken == null)
{
$scope.errortxt = result.resErr + " " + result.resuName;
}
},function(reason){
console.log(reason);
},function(error){
console.log(error);
});
};
当我在一些论坛中搜索时,他们将其存储在localstorage中,但我不清楚存储它。可以请任何人帮忙出去。
答案 0 :(得分:0)
您可以使用ngStorage
你必须将它注入工厂内并像这样使用它:
app.factory('authenticationSvc', ["$http","$q","$window","$location","$rootScope", "$localStorage", function($http,$q,$window,$location,$rootScope, $localStorage){
$localStorage.set('jwt', yourjwt);
$localStorage.get('jwt');
}])