Last active
January 9, 2025 20:27
-
-
Save greatb/c791796c0eba0916e34c536ab65802f8 to your computer and use it in GitHub Desktop.
Injectable CookieService class for Angular2
Update as commented by @sketchthat
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":"");
}
Good my friend.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 15
Is the script meant to be searching for whitespace? If so shouldn't the regex be
\s+
instead of\s\+
I was having an issue using the
getCookie
, once I adjusted this line the service worked as expected.