Cookie is one of the persistent storage in web client. It can ensure data persistent even page refresh. Compare with Local storage, it has additional security as it natively support expire date time. As contract, it’s size is limited on 4KB only.
Angular do not support cookie natively by default, so need to create service to handle it.
import { Injectable } from '@angular/core'; import { ObjectChecker } from '../utilities/object-checker'; @Injectable({ providedIn: 'root' }) export class CookieService { public getCookie(cookieName: string): string | null { let result = null; let cookies: string[] = document.cookie.split(";"); cookies.forEach(o=> { let cookie: string[] = o.split("="); let name: string = cookie[0].trim(); if (name === cookieName) { result = cookie[1]; } }); return result; } public setCookie(name: string, value: string) : boolean { document.cookie = `${name}=${value}; Secure;`; return true; } public deleteCookie(name: string) : boolean { return this.setCookie(name, "=; expires = Thu, 01 Jan 1970 00:00:00 UTC"); } public clearCookies() : boolean { let cookies: string[] = document.cookie.split(";"); cookies.forEach(o=> { let cookie: string[] = o.split("="); let name: string = cookie[0].trim(); this.deleteCookie(name); }); return true; } public hasCookie(name: string) : boolean { return !ObjectChecker.isNullOrUndefined(this.getCookie(name)); } }
Usage
constructor( private cookieService: CookieService ) { this.cookieService.clearCookies(); } test() : void { this.cookieService.setCookie("key", "value"); }); }
Leave a Reply