Skip to content

Instantly share code, notes, and snippets.

@bvandenbon
Last active December 4, 2020 10:29
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save bvandenbon/91d3e6d11363c08154b93f95eb4e9a0f to your computer and use it in GitHub Desktop.
Save bvandenbon/91d3e6d11363c08154b93f95eb4e9a0f to your computer and use it in GitHub Desktop.
CookieService
import { Injectable } from '@angular/core';
@Injectable()
export class CookieService {
constructor() {
}
set(key: string, value: string): void;
set(key: string, value: string, expires: Date): void;
set(key: string, value: string, expires?: Date): void {
let cookieValue = `${key}=${value}`;
if (expires) cookieValue += `;expires='${expires.toUTCString()}'`
document.cookie = cookieValue;
}
setWithExpiryInYears(key: string, value: string, expires: number) {
this.setWithExpiryInDays(key, value, expires * 365);
}
setWithExpiryInDays(key: string, value: string, expires: number) {
this.setWithExpiryInHours(key, value, expires * 24);
}
setWithExpiryInHours(key: string, value: string, expires: number) {
this.setWithExpiryInMinutes(key, value, expires * 60);
}
setWithExpiryInMinutes(key: string, value: string, expires: number) {
this.setWithExpiryInSeconds(key, value, expires * 60);
}
setWithExpiryInSeconds(key: string, value: string, expires: number) {
this.setWithExpiryInMiliseconds(key, value, expires * 1000);
}
setWithExpiryInMiliseconds(key: string, value: string, expires: number) {
var expireDate = new Date();
var time = expireDate.getTime() + expires;
expireDate.setTime(time);
this.set(key, value, expireDate);
}
get(key: string): string {
const decodedCookie: string = decodeURIComponent(document.cookie);
const pairs: string[] = decodedCookie.split(/;\s*/);
const prefix = `${key}=`;
for (const pair of pairs) {
if (pair.indexOf(prefix) == 0) {
return pair.substring(prefix.length);
}
}
return "";
}
}
@ORLAN07
Copy link

ORLAN07 commented Mar 27, 2019

thanks, like...

@lathionjb
Copy link

Nice one thx

@rabindranathforcast
Copy link

did you define delete method? or something similar to deleteAll ? looks good

@bvandenbon
Copy link
Author

@rabindranathforcast

I think you would just need to add the following 2 methods. (not tested).

a delete should be as follows:

  delete(key: string): void {
    document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
  }

to delete all cookies, maybe something like this:

  deleteAll(): void {
    const cookies = document.cookie.split(";");
    for (let i = 0; i < cookies.length; i++) {
      const key = (cookies[i].split("=")[0]);
      this.delete(key);
    }
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment