如何在AngularJS中设置cookie的过期日期 [英] How to set expiration date for cookie in AngularJS

查看:322
本文介绍了如何在AngularJS中设置cookie的过期日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. 我们希望在Cookie中存储用户的授权信息,而不是在浏览器刷新(F5)时丢失。

  1. We want to store User's Authorization information in cookie which should not be lost upon refresh (F5) of browser.

如果用户在登录时选择了记住我复选框,我们希望将授权信息存储在永久Cookie中。

We want to store authorization info in "permanent-cookie" in case user has opted for "Remember Me" check box at the time of log-on.


推荐答案

对于1.4:
如在这里的注释和下面的其他人,从1.4,Angular的本地cookie支持现在提供修改Cookie的能力:

For 1.4: As noted in the comment here and others below, as of 1.4, Angular's native cookie support now provides the ability to edit cookies:


由于38fbe3ee,$ cookies将不再公开属性,
表示当前浏览器cookie值。 $ cookies不再轮询
浏览器更改cookie,不再将cookie
值复制到$ cookies对象上。

Due to 38fbe3ee, $cookies will no longer expose properties that represent the current browser cookie values. $cookies no longer polls the browser for changes to the cookies and no longer copies cookie values onto the $cookies object.

因为轮询是昂贵的,并且导致
问题

实际浏览器cookie值不正确地同步(添加原来
的原因是允许不同选项卡之间的通信,但是有
更好的方法今天这样做,例如localStorage。)

This was changed because the polling is expensive and caused issues with the $cookies properties not synchronizing correctly with the actual browser cookie values (The reason the polling was originally added was to allow communication between different tabs, but there are better ways to do this today, for example localStorage.)

$ cookies上的新API如下:

The new API on $cookies is as follows:

get put getObject putObject getAll remove你必须明确使用上面的
方法来访问cookie数据。这也意味着你
不能再观察$ cookies中的属性来检测
在浏览器cookie上发生的变化。

get put getObject putObject getAll remove You must explictly use the methods above in order to access cookie data. This also means that you can no longer watch the properties on $cookies to detect changes that occur on the browsers cookies.

此功能一般只需要第三方库
在运行时以编程方式更改cookie。如果你依赖这个
,那么你必须写出可以对第三方
库做出反应的代码,或者实现你自己的投票
机制。

This feature is generally only needed if a 3rd party library was programmatically changing the cookies at runtime. If you rely on this then you must either write code that can react to the 3rd party library making the changes to cookies or implement your own polling mechanism.

实际实现是通过 $ cookiesProvider 对象,您可以通过 put 呼叫。

The actual implementation is done via a $cookiesProvider object, which can be passed via the put call.

对于1.3及以下版本:
对于那些已经尽力避免加载jQuery插件的人,这似乎是一个很好的替代角度 - https://github.com/ivpusic/angular-cookie

For 1.3 and below: For those of you who have done your best to avoid having to load jQuery plugins, this appears to be a nice replacement for angular - https://github.com/ivpusic/angular-cookie

这篇关于如何在AngularJS中设置cookie的过期日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆