gpt4 book ai didi

javascript - 如何在 AngularJS 中存储用户 session ?

转载 作者:可可西里 更新时间:2023-11-01 02:16:21 27 4
gpt4 key购买 nike

我刚刚开始使用 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 noneed to [...] wrap the model in accessors methods. Just plain oldJavaScript here." Now you can enjoy the same benefit while achievingdata persistence with Web Storage.

sessionStorage - We got this often-overlooked buddy covered.

Cleanly-Authored Code - Written in the Angular Way, well-structuredwith testability in mind.

No Cookie Fallback - With Web Storage being readily available in allthe browsers AngularJS officially supports, such fallback is largelyredundant.

示例如下所示

Working Demo

var eS = angular.module('exampleStore', ['localStorage']);

关于javascript - 如何在 AngularJS 中存储用户 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23682511/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com