角饼干


Answers:


76

我结束了创建自己的函数:

@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();
        }
    }
}

5
下次再注射一次:)
弗朗西斯·马诺伊·费纳多

17
也许您可以发布自己的具有可注射功能的解决方案,这对其他需要可注射功能的人来说非常有用:)
Miquel

这必须是一个组成部分吗?您为什么不使其成为可注射服务?
Ben Bozorg

可以,但是也有html和css显示同意标语。它似乎更像是组件而不是服务。您也可以提供服务,但应该是一种抽象的服务:)
Miquel

6
我根据上述答案创建了可注射服务:gist.github.com/greatb/c791796c0eba0916e34c536ab65802f8
Bala

43

更新: 现已弃用angular2-cookie。请改用我的ngx-cookie

旧答案:

这是angular2-cookie,它是我创建的Angular 1$cookies服务(加上removeAll()方法)的确切实现。它使用相同的方法,仅在带有Angular 2逻辑的打字稿中实现。

您可以将其作为服务注入componentsproviders数组中:

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

它在后台使用了角度1逻辑和方法。因此,它采用了更具角度的方式。它还具有$ cookies服务中的所有方法,以及删除所有方法。它还提供了全局和参数选项。这是一项服务。
salem

ngx-cookie似乎也没有更新。
杰普

它终于更新了。开发人员忙于其他工作,他也有点懒:D
s.alem

11

是的,这是一个ng2-cookie

用法:

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');

1
他们的API已更改为以下文档:github.com/BCJTI/ng2-cookies/wiki/Minimum-running-example
etayluz

8

使用NGX Cookie服务

安装此软件包: 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,您到目前为止是否使用过这项服务?因为我有一个问题,希望您能帮助我。
Jo先生

我已经安装了ngx-service和Cookie同意书。我现在正努力以选择加入的方式来实现它。如果用户按下拒绝Cookie按钮,我尝试删除所有cookie,但是它们将以某种方式重新设置。那么您知道该如何正确执行此操作吗?
Jo先生


看来版本10.1.1会产生错误Uncaught TypeError: Object(...) is not a function。我使用版本2.1.0来使代码正常工作。检查 github.com/stevermeister/ngx-cookie-service/issues/103
Manu Chadha

5

我将Miquels Version Injectable作为服务:

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和安全标志?
iniravpatel


0

要读取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 "";
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.