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?
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?
Câu trả lời:
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();
}
}
}
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 $cookies
dị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 providers
mả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
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');
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ó!
10.1.1
tạ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
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();
}
}
}
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
Để đọ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 "";