我一直在四处寻找Angular Cookie,但找不到如何在Angular中实现Cookie管理。有什么方法可以管理cookie(例如AngularJS中的$ cookie)吗?
Answers:
我结束了创建自己的函数:
@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();
}
}
}
更新: 现已弃用angular2-cookie。请改用我的ngx-cookie。
旧答案:
这是angular2-cookie,它是我创建的Angular 1$cookies
服务(加上removeAll()
方法)的确切实现。它使用相同的方法,仅在带有Angular 2逻辑的打字稿中实现。
您可以将其作为服务注入componentsproviders
数组中:
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-cookie
用法:
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');
使用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
}
而已!
10.1.1
会产生错误Uncaught TypeError: Object(...) is not a function
。我使用版本2.1.0
来使代码正常工作。检查 github.com/stevermeister/ngx-cookie-service/issues/103
我将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();
}
}
}
将数据存储到 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/zh-CN/docs/Web/API/Window/sessionStorage
要读取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 "";