Angular cookies
I ended creating my own functions:
@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();
}
}
}
Update: angular2-cookie is now deprecated. Please use my ngx-cookie instead.
Old answer:
Here is angular2-cookie which is the exact implementation of Angular 1 $cookies
service (plus a removeAll()
method) that I created. It is using the same methods, only implemented in typescript with Angular 2 logic.
You can inject it as a service in the components providers
array:
import {CookieService} from 'angular2-cookie/core';
@Component({
selector: 'my-very-cool-app',
template: '<h1>My Angular2 App with Cookies</h1>',
providers: [CookieService]
})
After that, define it in the consturctur as usual and start using:
export class AppComponent {
constructor(private _cookieService:CookieService){}
getCookie(key: string){
return this._cookieService.get(key);
}
}
You can get it via npm:
npm install angular2-cookie --save