【问题标题】:Angular cookies角饼干
【发布时间】:2016-03-21 18:28:06
【问题描述】:

我一直在寻找 Angular cookie,但我一直无法找到如何在 Angular 中实现 cookie 管理。有没有办法管理 cookie(比如 AngularJS 中的 $cookie)?

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

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

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

【讨论】:

  • 下次可注射:)
  • 也许您可以发布您自己的具有可注射功能的解决方案,这对于需要可注射的其他人来说会很棒:)
  • 这必须是一个组件吗?你为什么不让它成为一个可注入的服务呢?
  • 我已经根据上面的答案创建了可注入服务:gist.github.com/greatb/c791796c0eba0916e34c536ab65802f8
  • 如何设置 HttpOnly 和安全标志?
【解决方案2】:

更新: 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

【讨论】:

  • 与ng2-cookies有什么区别?
  • 它在幕后使用 angular 1 逻辑和方法。所以它以更角度的方式。它还具有 $cookies 服务中的所有方法,以及 remove all 方法。它还提供全局和参数选项。这是一项服务。
  • ngx-cookie 似乎也不再更新了。
  • 它终于更新了。开发人员忙于其他事情,他也有点懒:D
【解决方案3】:

使用 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,到目前为止,您使用过这项服务吗?因为我有一个问题,希望你能帮助我。
  • 我已经安装了 ngx-service 和 cookie 同意。我现在正在努力以选择加入的方式实施它。如果用户按下拒绝 cookie 按钮,我尝试删除所有 cookie,但它们会以某种方式重新设置。那么你知道这应该如何以正确的方式完成吗?
  • 似乎版本10.1.1 产生错误Uncaught TypeError: Object(...) is not a function。我使用版本2.1.0 来使代码正常工作。检查github.com/stevermeister/ngx-cookie-service/issues/103
  • @ManuChadha 您是否检查了针对不同子域的解决方案?例如,如果您将 cookie 设置为 domain.com,您是否会为 subdomain.domain.com 提供相同的 cookie?
【解决方案4】:

是的,这是一个 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');

【讨论】:

【解决方案5】:

我将 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 和安全标志?
【解决方案6】:

把数据存入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/en-US/docs/Web/API/Window/sessionStorage

【讨论】:

    【解决方案7】:

    为了读取 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 "";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      • 1970-01-01
      • 2015-06-06
      • 2010-09-15
      • 2010-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多