Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 cookies instead of localstorage

Tags:

I managed to make all work JWT auth, no problems there, but it only supports modern browsers, and I need Auth to work in all starting from IE9 and upwards.

I could not find any info or examples how to use cookies in Angular2. There is a simple example using localStorage for saving token, I need the same functionality but done with cookies.

Any help would be great, since there isn't anything on this on the net.

this.http.post("http://localhost:3001/sessions/create", creds, { headers: header })
    .map(res => res.json())
    .subscribe(
      data => localStorage.setItem('id_token',data.id_token),
      err => this.logError(err),
      () => console.log("Auth is completed!")
    );
like image 963
Milan Milanovic Avatar asked Nov 03 '15 09:11

Milan Milanovic


2 Answers

A simple way to solve this is use this lib:

https://www.npmjs.com/package/ng2-cookies

To install this library, run:

$ npm install ng2-cookies

Usage:

import { Cookie } from 'ng2-cookies/ng2-cookies';

Cookie.set('cookieName', 'cookieValue');
Cookie.set('cookieName', 'cookieValue', 10 /*days from now*/);
Cookie.set('cookieName', 'cookieValue', 10, '/myapp/', 'mydomain.com');

let myCookie = Cookie.get('cookieName');

/*
* List of cookies as Object, like: { cookieName: "cookieValue", cookieName2: "cookieValue2" ... etc }
*/
let cookielist = Cookie.getAll();

Cookie.delete('cookieName');
Cookie.deleteAll();
like image 157
Exdcarca Avatar answered Oct 08 '22 08:10

Exdcarca


I implemented the cookie service with the functions from Angular 1 to the Angular 2 as an injectable service. Also added a removeAll function as a plus. You can get it with:

npm install angular2-cookie --save

After injecting it as a service, you can use the methods as in Angular 1:

this._cookieService.get(key);
this._cookieService.getObject(key);
// Other available methods are
// put(), putObject(), remove() and removeAll()

You can check the readme part for examples and available functions.

https://github.com/salemdar/angular2-cookie

like image 41
s.alem Avatar answered Oct 08 '22 08:10

s.alem