Skip to content

Instantly share code, notes, and snippets.

@greatb
Last active April 14, 2023 17:17
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save greatb/c791796c0eba0916e34c536ab65802f8 to your computer and use it in GitHub Desktop.
Save greatb/c791796c0eba0916e34c536ab65802f8 to your computer and use it in GitHub Desktop.
Injectable CookieService class for Angular2
@greatb
Copy link
Author

greatb commented Jan 13, 2017

@sketchthat
Copy link

Line 15

c = ca[i].replace(/^\s\+/g, "");

Is the script meant to be searching for whitespace? If so shouldn't the regex be \s+ instead of \s\+

c = ca[i].replace(/^\s+/g, "");

I was having an issue using the getCookie, once I adjusted this line the service worked as expected.

@greatb
Copy link
Author

greatb commented May 8, 2017

Update as commented by @sketchthat

@juanwhite99
Copy link

juanwhite99 commented Jun 21, 2017

this is great, thanks!, I have made some changes to set and delete cookie, please check

  public deleteCookie(cookieName) {
    this.setCookie({name:cookieName,value:'',expireDays:-1});
  }

  /**
   * Expires default 1 day 
   * If params.session is set and true expires is not added
   * If params.path is not set or value is not greater than 0 its default value will be root "/"
   * Secure flag can be activated only with https implemented
   * Examples of usage:
   * {service instance}.setCookie({name:'token',value:'abcd12345', session:true }); <- This cookie will not expire
   * {service instance}.setCookie({name:'userName',value:'John Doe', secure:true }); <- If page is not https then secure will not apply
   * {service instance}.setCookie({name:'niceCar', value:'red', expireDays:10 }); <- For all this examples if path is not provided default will be root
   */
  public setCookie(params:any) 
  {
    let d: Date = new Date();
    d.setTime(d.getTime() + (params.expireDays ? params.expireDays:1) * 24 * 60 * 60 * 1000); 
    document.cookie = 
        (params.name? params.name:'') + "=" + (params.value?params.value:'') + ";"
        + (params.session && params.session == true ? "" : "expires=" + d.toUTCString() + ";")
        + "path=" +(params.path && params.path.length > 0 ? params.path:"/") + ";"
        + (location.protocol === 'https:' && params.secure && params.secure == true ? "secure":"");
  }

@newguru-25
Copy link

Good my friend.

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