Angular cookies

117

我一直在寻找Angular的cookies,但是我没有找到如何在Angular中实现cookie管理的方法。是否有任何方式可以管理cookies(类似于AngularJS中的$cookie)?


8
Angular2没有任何原生的库/服务来处理cookies。首选的方法是使用JWT / LocalStorage。https://github.com/auth0/angular2-authentication-sample - stan
8个回答

100

我最终创建了自己的函数:

@Component({
    selector: 'cookie-consent',
    template: cookieconsent_html,
    styles: [cookieconsent_css]
})
export class CookieConsent {
    private isConsented: boolean = false;

    constructor() {
        this.isConsented = this.getCookie(COOKIE_CONSENT) === '1';
    }

    private getCookie(name: string) {
        let ca: Array<string> = document.cookie.split(';');
        let caLen: number = ca.length;
        let cookieName = `${name}=`;
        let c: string;

        for (let i: number = 0; i < caLen; i += 1) {
            c = ca[i].replace(/^\s+/g, '');
            if (c.indexOf(cookieName) == 0) {
                return c.substring(cookieName.length, c.length);
            }
        }
        return '';
    }

    private deleteCookie(name) {
        this.setCookie(name, '', -1);
    }

    private setCookie(name: string, value: string, expireDays: number, path: string = '') {
        let d:Date = new Date();
        d.setTime(d.getTime() + expireDays * 24 * 60 * 60 * 1000);
        let expires:string = `expires=${d.toUTCString()}`;
        let cpath:string = path ? `; path=${path}` : '';
        document.cookie = `${name}=${value}; ${expires}${cpath}`;
    }

    private consent(isConsent: boolean, e: any) {
        if (!isConsent) {
            return this.isConsented;
        } else if (isConsent) {
            this.setCookie(COOKIE_CONSENT, '1', COOKIE_CONSENT_EXPIRE_DAYS);
            this.isConsented = true;
            e.preventDefault();
        }
    }
}

7
下次请将其制成可注射的形式 :) - Francis Manoj Fernnado
29
也许你可以发布一个带有可注入功能的自己的解决方案,这对其他需要可注入功能的人来说会非常棒 :) - Miquel
2
这必须是一个组件吗?为什么不将其设置为可注入服务? - Ben Bozorg
10
我已经根据上面的答案创建了可注入服务:https://gist.github.com/greatb/c791796c0eba0916e34c536ab65802f8 - Bala
1
如何设置 HttpOnly 和 secure 标志? - iniravpatel
显示剩余9条评论

44

更新:angular2-cookie现已过时,请使用我的ngx-cookie代替。

原回答:

这里是angular2-cookie,它是我创建的与Angular 1 $cookies服务完全相同的实现(加上removeAll()方法)。它使用相同的方法,只是用Angular 2逻辑以typescript实现。

您可以将其作为服务注入到组件的providers数组中:

import {CookieService} from 'angular2-cookie/core';

@Component({
    selector: 'my-very-cool-app',
    template: '<h1>My Angular2 App with Cookies</h1>',
    providers: [CookieService]
})

在那之后,像往常一样在构造函数中定义它并开始使用:

export class AppComponent { 
  constructor(private _cookieService:CookieService){}

  getCookie(key: string){
    return this._cookieService.get(key);
  }
}
您可以通过npm获取它:
npm install angular2-cookie --save

1
ng2-cookies 有什么不同? - Miquel
它在幕后使用了 Angular 1 的逻辑和方法。因此,它更符合 Angular 的方式。它还包含了 $cookies 服务中的所有方法,以及一个删除所有方法。它还提供了全局和参数选项,并且是一个服务。 - s.alem
1
ngx-cookie 似乎也没有更新了。 - Jeppe
1
它终于更新了。开发人员忙于其他事情,而且他也有点懒:D - s.alem

26

使用NGX Cookie Service

安装此包:npm install ngx-cookie-service --save

将cookie服务添加到您的app.module.ts作为提供者:

import { CookieService } from 'ngx-cookie-service';
@NgModule({
  declarations: [ AppComponent ],
  imports: [ BrowserModule, ... ],
  providers: [ CookieService ],
  bootstrap: [ AppComponent ]
})
然后调用你的组件:
import { CookieService } from 'ngx-cookie-service';

constructor( private cookieService: CookieService ) { }

ngOnInit(): void {
  this.cookieService.set( 'name', 'Test Cookie' ); // To Set Cookie
  this.cookieValue = this.cookieService.get('name'); // To Get Cookie
}

就是这样!


嗨,Deepak,你之前有使用过这个服务吗?因为我有一个问题,希望你能帮助我。 - Mr. Jo
我已经安装了ngx-service和cookie consent。现在我正在艰难地尝试以选择加入的方式来实现它。我已经尝试过如果用户按下拒绝cookie按钮则删除所有cookie,但它们会以某种方式重新设置。所以,您知道应该如何正确地完成吗? - Mr. Jo
这是我的问题:https://stackoverflow.com/questions/61656421/how-can-i-block-cookies-for-beeing-stored-in-the-browser-in-angular - Mr. Jo
似乎版本 10.1.1 会出现错误 Uncaught TypeError: Object(...) is not a function。我使用版本 2.1.0 使代码正常工作。请查看 https://github.com/stevermeister/ngx-cookie-service/issues/103。 - Manu Chadha
@ManuChadha 你有检查过关于不同子域的解决方案吗?例如,如果您将cookie设置为domain.com,那么您是否可以在subdomain.domain.com中使用相同的cookie? - ael

13

好的,这里有一个ng2-cookies

用法:

import { Cookie } from 'ng2-cookies/ng2-cookies';

Cookie.setCookie('cookieName', 'cookieValue');
Cookie.setCookie('cookieName', 'cookieValue', 10 /*days from now*/);
Cookie.setCookie('cookieName', 'cookieValue', 10, '/myapp/', 'mydomain.com');

let myCookie = Cookie.getCookie('cookieName');

Cookie.deleteCookie('cookieName');

2
他们的API已经改变,这里是文档链接:https://github.com/BCJTI/ng2-cookies/wiki/Minimum-running-example - etayluz

8

我把Miquels版本改成了可注入服务的形式:

import { Injectable } from '@angular/core';

@Injectable()
export class CookiesService {

    isConsented = false;

    constructor() {}

    /**
     * delete cookie
     * @param name
     */
    public deleteCookie(name) {
        this.setCookie(name, '', -1);
    }

    /**
     * get cookie
     * @param {string} name
     * @returns {string}
     */
    public getCookie(name: string) {
        const ca: Array<string> = decodeURIComponent(document.cookie).split(';');
        const caLen: number = ca.length;
        const cookieName = `${name}=`;
        let c: string;

        for (let i  = 0; i < caLen; i += 1) {
            c = ca[i].replace(/^\s+/g, '');
            if (c.indexOf(cookieName) === 0) {
                return c.substring(cookieName.length, c.length);
            }
        }
        return '';
    }

    /**
     * set cookie
     * @param {string} name
     * @param {string} value
     * @param {number} expireDays
     * @param {string} path
     */
    public setCookie(name: string, value: string, expireDays: number, path: string = '') {
        const d: Date = new Date();
        d.setTime(d.getTime() + expireDays * 24 * 60 * 60 * 1000);
        const expires = `expires=${d.toUTCString()}`;
        const cpath = path ? `; path=${path}` : '';
        document.cookie = `${name}=${value}; ${expires}${cpath}; SameSite=Lax`;
    }

    /**
     * consent
     * @param {boolean} isConsent
     * @param e
     * @param {string} COOKIE
     * @param {string} EXPIRE_DAYS
     * @returns {boolean}
     */
    public consent(isConsent: boolean, e: any, COOKIE: string, EXPIRE_DAYS: number) {
        if (!isConsent) {
            return this.isConsented;
        } else if (isConsent) {
            this.setCookie(COOKIE, '1', EXPIRE_DAYS);
            this.isConsented = true;
            e.preventDefault();
        }
    }

}

如何设置 HttpOnly 和 secure 标志? - iniravpatel

3

将数据存储到sessionStorage中也是有益的。

// Save data to sessionStorage
sessionStorage.setItem('key', 'value');

// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');

// Remove saved data from sessionStorage
sessionStorage.removeItem('key');

// Remove all saved data from sessionStorage
sessionStorage.clear();

详细信息请参见https://developer.mozilla.org/zh-CN/docs/Web/API/Window/sessionStorage


1

我为了读取cookie对Miquel版本进行了一些修改,但它对我来说无法工作:

getCookie(name: string) {
        let ca: Array<string> = document.cookie.split(';');
        let cookieName = name + "=";
        let c: string;

        for (let i: number = 0; i < ca.length; i += 1) {
            if (ca[i].indexOf(name, 0) > -1) {
                c = ca[i].substring(cookieName.length +1, ca[i].length);
                console.log("valore cookie: " + c);
                return c;
            }
        }
        return "";

0

我最简单的CookieService,仅支持读取

import { DOCUMENT } from "@angular/common";
import { Inject, Injectable } from "@angular/core";

@Injectable({ providedIn: 'root' })
export class CookieService {

    public constructor(@Inject(DOCUMENT) private document: Document) { }

    public get(name: string) {
        const cookies = this.document.cookie.split('; ')
        for (let i = 0; i < cookies.length; i++) {
            const [key, value] = cookies[i].split('=');
            if (key === name) {
                return decodeURIComponent(value);
            }
        }
        return null;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接