角饼干

Miq*_*uel 64 javascript typescript angular

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

Miq*_*uel 61

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

@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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 也许你可以发布自己的注射功能解决方案,这对于需要注射的人来说非常棒:) (14认同)
  • 下次让它成为注射剂:) (5认同)
  • 我已根据上述答案创建了注射服务:https://gist.github.com/greatb/c791796c0eba0916e34c536ab65802f8 (5认同)
  • 这必须是一个组件吗?为什么不把它变成可注入的服务呢? (2认同)

s.a*_*lem 38

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

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

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

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

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

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

  getCookie(key: string){
    return this._cookieService.get(key);
  }
}
Run Code Online (Sandbox Code Playgroud)

你可以通过npm得到它:

npm install angular2-cookie --save
Run Code Online (Sandbox Code Playgroud)

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


Dee*_*ain 13

使用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 ]
})
Run Code Online (Sandbox Code Playgroud)

然后调用你的组件:

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
}
Run Code Online (Sandbox Code Playgroud)

就是这样!


Art*_*oms 11

是的,这是一个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');
Run Code Online (Sandbox Code Playgroud)

  • 他们的 API 已更改,以下是文档:https://github.com/BCJTI/ng2-cookies/wiki/Minimum-running-example (2认同)

mil*_*lan 7

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

}
Run Code Online (Sandbox Code Playgroud)