我刚刚开始使用 AngularJS,我正在尝试将用户 session 存储在我的 AngularApp 上。
提交用户名和密码的第一步有效。
之后,我将从服务中检索到的 username
存储在 $rootScope
中。
下一页可以显示存储的用户名
。
但是在刷新之后,$rootScope
是空的。
我正在尝试做一个尽可能简单的身份验证系统。
myApp.controller('loginController', ['$scope', '$rootScope', '$location', 'AuthService', '$route',
function ($scope, $rootScope, $location, AuthService, $route) {
$scope.login = function (credentials) {
AuthService.login(credentials).then(function (response) {
if(response.data == "0"){
alert("Identifiant ou mot de passe incorrect");
}
else {
// response.data is the JSON below
$rootScope.credentials = response.data;
$location.path("/");
}
});
};
}]);
AuthService.login()
发出一个 $http
请求。
JSON
{user_id: 1, user_name: "u1", user_display_name: "Steffi"}
HTML:
<div>Welcome {{ credentials.user_display_name }}!</div>
我尝试了很多教程,但我无法使 session 正常工作。 我已经使用过 UserApp,但它对我来说不好。我想创建自己的简单身份验证。
最佳答案
你可以使用
ngStorage
An AngularJS module that makes Web Storage working in the Angular Way. Contains two services: $localStorage and $sessionStorage.
Differences with Other Implementations
No Getter 'n' Setter Bullshit - Right from AngularJS homepage: "Unlike other frameworks, there is no need to [...] wrap the model in accessors methods. Just plain old JavaScript here." Now you can enjoy the same benefit while achieving data persistence with Web Storage.
sessionStorage - We got this often-overlooked buddy covered.
Cleanly-Authored Code - Written in the Angular Way, well-structured with testability in mind.
No Cookie Fallback - With Web Storage being readily available in all the browsers AngularJS officially supports, such fallback is largely redundant.
示例如下所示
var eS = angular.module('exampleStore', ['localStorage']);
关于javascript - 如何在 AngularJS 中存储用户 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23682511/