Skip to content

Instantly share code, notes, and snippets.

@hassansw
Created July 4, 2018 09:05
Show Gist options
  • Save hassansw/6ab695703007b3b6cd67fc96789616d7 to your computer and use it in GitHub Desktop.
Save hassansw/6ab695703007b3b6cd67fc96789616d7 to your computer and use it in GitHub Desktop.
Cookies Injectable
import { Injectable } from '@angular/core';
@Injectable()
export class CookieService {
constructor() { }
public getCookie(name: string): any | null {
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 null;
}
public deleteCookie(name) {
this.setCookie(name, "", -1);
}
public 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();
document.cookie = name + "=" + value + "; " + expires + (path.length > 0 ? "; path=" + path : "");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment