Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular cookies

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)?

like image 891
Miquel Avatar asked Dec 15 '15 19:12

Miquel


People also ask

How do I use cookies in angular 8?

To save information in the cookies you will need to use set() function. It takes two parameters: the name of the key and the value of the key. The get() function is used to get a single value from a cookie. To get all values, you can use the getAll() function.

What are cookies used for?

Cookies are small pieces of text sent to your browser by a website you visit. They help that website remember information about your visit, which can both make it easier to visit the site again and make the site more useful to you.


Video Answer


1 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();         }     } } 
like image 148
Miquel Avatar answered Oct 31 '22 00:10

Miquel