[Typescript] Cookie handling in Angular

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");
    });
  }

 

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.