当前位置:  开发笔记 > 编程语言 > 正文

角饼干

如何解决《角饼干》经验,为你挑选了3个好方法。

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



1> Miquel..:

我结束了创建自己的功能:

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


也许你可以发布自己的注射功能解决方案,这对于需要注射的人来说非常棒:)
下次让它成为注射剂:)
我已根据上述答案创建了注射服务:https://gist.github.com/greatb/c791796c0eba0916e34c536ab65802f8

2> s.alem..:

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

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

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

@Component({
    selector: 'my-very-cool-app',
    template: '

My Angular2 App with Cookies

', providers: [CookieService] })

之后,像往常一样在consturctur中定义它并开始使用:

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

  getCookie(key: string){
    return this._cookieService.get(key);
  }
}

你可以通过npm得到它:

npm install angular2-cookie --save

编辑:angular2-cookie现已弃用.请改用ngx-cookie.



3> Arturs Soms..:

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

推荐阅读
小白也坚强_177
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有