Cookie góc cạnh


81

Tôi đã tìm kiếm khắp nơi để tìm cookie Angular nhưng tôi không thể tìm thấy cách triển khai quản lý cookie trong Angular. Có cách nào để quản lý cookie (như $ cookie trong AngularJS) không?


7
Angular2 không có bất kỳ thư viện / dịch vụ gốc nào để xử lý cookie. Cách ưu tiên là sử dụng JWT / LocalStorage. github.com/auth0/angular2-authentication-sample
stan

Câu trả lời:


76

Tôi đã kết thúc việc tạo các chức năng của riêng mình:

@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
làm cho nó một lần sau tiêm :)
Francis Manoj Fernnado

17
Có lẽ bạn có thể gửi giải pháp của riêng bạn với chức năng tiêm, đó sẽ là tuyệt vời cho những người khác cần nó tiêm :)
Miquel

Đây có phải là một thành phần? Tại sao bạn không biến nó thành một dịch vụ tiêm?
Ben Bozorg

Có thể được, nhưng điều này cũng có html và css để hiển thị biểu ngữ đồng ý. Nó có vẻ giống một thành phần hơn là một dịch vụ. Bạn có thể làm cho một dịch vụ cũng có, nhưng phải là một một trừu tượng hơn :)
Miquel

6
Tôi đã tạo ra các dịch vụ tiêm dựa trên câu trả lời ở trên: gist.github.com/greatb/c791796c0eba0916e34c536ab65802f8
Bala

43

Cập nhật: angle2-cookie hiện không được dùng nữa. Vui lòng sử dụng ngx-cookie của tôi thay thế.

Câu trả lời cũ:

Đây là angle2-cookie , là cách triển khai chính xác của $cookiesdịch vụ Angular 1 (cùng với một removeAll()phương thức) mà tôi đã tạo. Nó đang sử dụng các phương pháp tương tự, chỉ được thực hiện trong bảng chữ với logic Angular 2.

Bạn có thể đưa nó vào làm dịch vụ trong providersmảng thành phần :

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

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

Sau đó, xác định nó trong consturctur như bình thường và bắt đầu sử dụng:

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

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

Bạn có thể lấy nó qua npm:

npm install angular2-cookie --save

1
Sự khác biệt với ng2-cookie là gì?
Miquel

Nó đang sử dụng logic 1 góc cạnh và các phương pháp đằng sau hậu trường. Vì vậy, nó là một cách góc cạnh hơn. Ngoài ra, nó có tất cả các phương thức từ dịch vụ $ cookies, cùng với một phương thức loại bỏ tất cả. Ngoài ra nó cung cấp các tùy chọn toàn cầu và tham số. Và nó là một dịch vụ.
s.alem

ngx-cookie dường như cũng không được cập nhật nữa.
Jeppe

Nó cuối cùng đã được cập nhật. Nhà phát triển bận rộn với những thứ khác và anh ấy cũng hơi lười biếng: D
s.alem

11

Vâng, đây là một ng2-cookie

Sử dụng:

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 của họ đã thay đổi ở đây là tài liệu: github.com/BCJTI/ng2-cookies/wiki/Minimum-running-example
etayluz Ngày

8

Sử dụng Dịch vụ Cookie NGX

Inastall gói này: npm install ngx-cookie-service --save

Thêm dịch vụ cookie vào app.module.ts của bạn với tư cách là nhà cung cấp:

import { CookieService } from 'ngx-cookie-service';
@NgModule({
  declarations: [ AppComponent ],
  imports: [ BrowserModule, ... ],
  providers: [ CookieService ],
  bootstrap: [ AppComponent ]
})

Sau đó, gọi trong thành phần của bạn:

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
}

Đó là nó!


Xin chào Deepak, bạn đã làm việc với dịch vụ này cho đến nay chưa? Vì em có một thắc mắc mong anh / chị giải đáp giúp em.
Ông Jo

Tôi đã cài đặt cả dịch vụ ngx và đồng ý cookie. Tôi hiện đang gặp khó khăn trong việc triển khai nó theo cách chọn tham gia. Tôi đã thử xóa tất cả cookie nếu người dùng nhấn vào nút từ chối cookie nhưng bằng cách nào đó họ đang được thiết lập lại. Vì vậy, bạn có biết điều này nên được thực hiện như thế nào là đúng cách?
Ông Jo

Đây là câu hỏi của tôi về điều này: stackoverflow.com/questions/61656421/…
Ông Jo

Có vẻ như phiên bản 10.1.1tạo ra lỗi Uncaught TypeError: Object(...) is not a function. Tôi sử dụng phiên bản 2.1.0để mã hoạt động. Kiểm tra github.com/stevermeister/ngx-cookie-service/issues/103
Manu Chadha

5

Tôi đặt Miquels Phiên bản Injectable làm dịch vụ:

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

}

Làm thế nào để đặt cờ HttpOnly và an toàn?
iniravpatel

2

Nó cũng có lợi khi lưu trữ dữ liệu vào 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();

để biết chi tiết https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage


0

Để đọc một cookie, tôi đã thực hiện một số sửa đổi nhỏ đối với phiên bản Miquel không phù hợp với tôi:

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 "";
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.