Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular4x : ngx-cookie-service with expire parameter

I am using ngx-cookie-service component but as soon as i close the browser the cookies disappears, maybe i have to set the expire parameter but i can't get it , below what the the documentation says:

set( name: string, value: string, expires?: number | Date, path?: string, domain?: string, secure?: boolean ): void;

(I tried with number but it seems that doesn't work)

Thanks in advance.

like image 315
Gelso77 Avatar asked Apr 13 '18 13:04

Gelso77


2 Answers

I've solved it like that

this.expiredDate = new Date();
this.expiredDate.setDate( this.expiredDate.getDate() + 7 );

//write
this.cookieService.set( 'key',JSON.stringify('value'), this.expiredDate);

//read
console.log(JSON.parse(this.cookieService.get( 'key'));   

Remember to inject the cookieService

  import { CookieService } from 'ngx-cookie-service';
  constructor(private cookieService: CookieService) {}

Install

npm install angular2-cookie --save
like image 67
Gelso77 Avatar answered Sep 26 '22 02:09

Gelso77


Use number, which is the 3rd parameter, where the number represents the number of days until it expires.

For example, if you want the cookie to expire in 365 days, use:

this.cookieService.set('cookieName', cookieValue, 365);

Hope that helps!

like image 42
Justin F Avatar answered Sep 28 '22 02:09

Justin F