Javascript 如何在angular js的cookie中存储登录会话ID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30294654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:56:18  来源:igfitidea点击:

How to store login session id in cookie in angular js?

javascriptangularjssessioncookies

提问by iamtheDanger

I have the following piece of code where I am storing the login credentials of user in local storage along with his authority(whether he is admin or not).

我有以下一段代码,我将用户的登录凭据及其权限(无论他是否是管理员)存储在本地存储中。

.success(function (user) {
            localStorageService.set('localStorageUser', user.username);
            localStorageService.set('localStorageUserRole', user.authorities[0].authority);

            $rootScope.showMenu = true;
            $rootScope.user = user.username;

             if(localStorageService.get('localStorageUserRole') === 'ROLE_ADMIN'){
                 $rootScope.isAdmin = true;                  
             }
             else {
                 $rootScope.isAdmin = false;                     
             }                

            d.resolve();
        })

I want to know how I can store the user login session id in a cookie and also set an expiration date for the cookie in AngularJS.

我想知道如何将用户登录会话 ID 存储在 cookie 中,并在 AngularJS 中为 cookie 设置到期日期。

回答by Huy Hoang Pham

AngularJS have already provided a wrapper to work with cookies.

AngularJS 已经提供了一个包装器来处理 cookie。

You can visit this page to know how to add the ngCookies plug-in to your project: https://docs.angularjs.org/api/ngCookies

您可以访问此页面了解如何将 ngCookies 插件添加到您的项目中:https://docs.angularjs.org/api/ngCookies

First include angular-cookies.js in your HTML:

You can download this file from the following places:

Google CDN e.g.

//ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-cookies.js

Then load the module in your application by adding it as a dependent module:

angular.module('app', ['ngCookies']);

With that you're ready to get started!

首先在 HTML 中包含 angular-cookies.js:

您可以从以下位置下载此文件:

谷歌 CDN 例如

//ajax.googleapis.com/ajax/libs/angularjs/XYZ/angular-cookies.js

然后通过将其添加为依赖模块将模块加载到您的应用程序中:

angular.module('app', ['ngCookies']);

有了它,你就可以开始了!

The use of $cookie is very simple:

$cookie 的使用非常简单:

$cookies.put('user', user.username);
var username = $cookies.get('user');

//You can set the expired time with the third params
var today = new Date();
var expired = new Date(today);
expired.setDate(today.getDate() + 1); //Set expired date to tomorrow
$cookies.put('user', user.username, {expires : expired });

More about $cookies: https://docs.angularjs.org/api/ngCookies/service/$cookies

有关 $cookies 的更多信息:https: //docs.angularjs.org/api/ngCookies/service/$cookies