如何在 Angular 2 中为 cookie 添加过期时间(以小时为单位)?

How to add expiry time in hours for a cookie in Angular 2?

如何为 cookie 添加以小时为单位的过期时间,我可以用天来完成。

Cookie.set('SESSION_TOKEN', sessionToken, 6); // here 6 is days

我要几小时内。我希望 cookie 在 6 小时后过期。

Cookie.set('SESSION_TOKEN', sessionToken, 6(hours)); // 6 hours

下面是我正在使用的代码,但出现错误“'Date' 类型的参数无法分配给 'number' 类型的参数“

setCookie(userObject) {
    let expire = new Date();
    var time = Date.now() + ((3600 * 1000) * 6);
    expire.setTime(time);
    console.log("expire "+expire);
    Cookie.set('USER_NAME',Base64.encode(userObject.user.email),expire);
    Cookie.set('SESSION_TOKEN',userObject.sessionToken,expire);
}

据我所知,ng2-cookies 的当前版本不包含允许您定义小时而不是天的功能。因此你必须手动计算cookie的过期时间。

ng2-cookies/src/cookie.ts

/**
 * Save the Cookie
 *
 * @param  {string} name Cookie's identification
 * @param  {string} value Cookie's value
 * @param  {number} expires Cookie's expiration date in days from now or at a specific date from a Date object. If it's undefined the cookie is a session Cookie
 * @param  {string} path Path relative to the domain where the cookie should be avaiable. Default /
 * @param  {string} domain Domain where the cookie should be avaiable. Default current domain
 * @param  {boolean} secure If true, the cookie will only be available through a secured connection
 */
public static set(name: string, value: string, expires?: number | Date, path?: string, domain?: string, secure?: boolean) {

所以我想这样的事情可能会奏效。

import { Cookie } from 'ng2-cookies';

var expire = new Date();
var time = Date.now() + ((3600 * 1000) * 6); // current time + 6 hours ///
expire.setTime(time);

Cookie.set("test", "", expire);

我曾经这样做过,它对我有用。

 Cookie.set('SESSION_TOKEN',userObject.sessionToken,0.25);

实际上,如果我们给 1 它会持续 24 小时,所以我对其应用了数学逻辑,即持续 6 小时。

1 day -> 24 hrs
? day -> 6 hrs
(1*6)/24 -> 0.25 i.e. 6hrs

您也可以执行如下操作并以小时为单位进行设置以降低复杂性:

const now = new Date();
now.setHours(now.getHours() + 8);
Cookie.set('SESSION_TOKEN', sessionToken, now);

然后您可以通过更改 setHours 中的数字轻松地设置您喜欢的过期时间(以小时为单位):)