I've been looking all around for Angular cookies but I haven't been able to find how to implement cookies management in Angular. Is there any way to manage cookies (like $cookie in AngularJS)?
-
7Angular2 doesn't have any native library/service to handle cookies. The preferred way is to use JWT/LocalStorage. github.com/auth0/angular2-authentication-sample– stanDec 15, 2015 at 20:24
7 Answers
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();
}
}
}
-
7
-
27Maybe you could post your own solution with injectable functionality, that would be great for others needing it injectable :)– MiquelDec 5, 2016 at 9:58
-
2Does this have to be a component? Why don't you make it an injectable service? Dec 20, 2016 at 22:29
-
8I have created the injectable service based on the above answer : gist.github.com/greatb/c791796c0eba0916e34c536ab65802f8– BalaJan 13, 2017 at 0:40
-
1
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
-
1
-
It is using the angular 1 logic and methods behind the scenes. So it is in more angular way. Also it has all the methods from $cookies service, plus a remove all method. Also it provides global and parameter options. And it is a service.– s.alemMar 18, 2016 at 20:43
-
-
It it finally updated. The dev was busy with other stuff and he is also a little bit lazy :D– s.alemAug 10, 2020 at 8:08
Use NGX Cookie Service
Inastall this package: npm install ngx-cookie-service --save
Add the cookie service to your app.module.ts as a provider:
import { CookieService } from 'ngx-cookie-service';
@NgModule({
declarations: [ AppComponent ],
imports: [ BrowserModule, ... ],
providers: [ CookieService ],
bootstrap: [ AppComponent ]
})
Then call in your component:
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
}
That's it!
-
Hi Deepak, have you worked with this service so far? Because I've a question and hope you can help me.– Mr. JoMay 7, 2020 at 12:27
-
I've installed both the ngx-service and cookie consent. I'm now struggling hard with implementing it the opt-in way. I've tried deleting all cookies if the user presses the decline cookies button but they're getting re-set somehow. So do you know how this should be done the correct way?– Mr. JoMay 7, 2020 at 19:08
-
This is my question about this: stackoverflow.com/questions/61656421/…– Mr. JoMay 7, 2020 at 19:08
-
It seems the version
10.1.1
creates errorUncaught TypeError: Object(...) is not a function
. I use version2.1.0
to get the code working. Check github.com/stevermeister/ngx-cookie-service/issues/103 Oct 16, 2020 at 19:11 -
@ManuChadha Did you check your solution regarding to different subdomains? If you set a cookie for example to domain.com, will you have the same cookie available for subdomain.domain.com ?– aelNov 27, 2021 at 12:49
Yeah, here is one ng2-cookies
Usage:
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');
-
2Their API has changed here are the docs: github.com/BCJTI/ng2-cookies/wiki/Minimum-running-example– etayluzMar 8, 2017 at 5:09
I make Miquels Version Injectable as service:
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();
}
}
}
It is also beneficial to store data into 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();
for details https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
For read a cookie i've made little modifications of the Miquel version that doesn't work for me:
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 "";