BCJTI / ng2-cookies

Simple library to deal with cookies in Angular2
64 stars 31 forks source link

set method expires is not working #59

Closed ratikanta131 closed 6 years ago

ratikanta131 commented 6 years ago

I gave the expiration some minutes from now and it did not get expired.

Bigous commented 6 years ago

could you post here the snippet that is failing?

awanczowski commented 6 years ago

Hello @Bigous ,

I am also experiencing a similar issue. The expiration is always set to session. I am currently using Chrome build 63.0.3239.108 (Official Build) (64-bit) (cohort: 63_win_108)

   "ng2-cookies": {
      "version": "1.0.12",
      "resolved": "https://registry.npmjs.org/ng2-cookies/-/ng2-cookies-1.0.12.tgz",
      "integrity": "sha1-Pz5hPgE3sGSbcFxngHS0vQgUnMw="
    }

Cookie.set('test_cookie', 'test', new Date().getTime() + 1000);

capture

Thanks, Drew

awanczowski commented 6 years ago

The above issue actually can be resolved by wrapping the newly calculated offset in another new date call.

new Date(new Date().getTime() + 1000) this will set the experiation time correctly.

Bigous commented 6 years ago

All right, Now I figured out what's happening tks to @awanczowski .

Ok, this library accepts both Date object and Number for expiration parameter. When you pass a Date object it assumes that it's the date you want the cookie to expire. Bun when you pass a Number, it assumes that the number is in days from now you want the cookie to expire (sorry about that - it's only quoted at the JSDocs of the method and can lead to misconception).

So, when you pass new Date().getTime() + 1000, which is a Number, it will transform it to new Date(new Date().getTime() + (new Date().getTime() + 1000) * 1000 * 60 * 60 * 24) and will take like forever to expire.

If you want 1s for expiration only, you can pass the exactDate object as @awanczowski posted (and thanks again) or you can do it passing 1.0/24/60/60. Both will work correctly.

We did it because normally you wanna set the expiration for cookies for 1 or 2 days (and if you want 6h, just pass 0.25).