Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving cookie using angular 4

I have a ldap based authentication in place where if the user credentials are matched , a bearer token and an userId is received as a response in JSON format. Now I need to save these values in cookie. I am using angular 4. I could not find any cookie related example for angular 4.

like image 402
user9040429 Avatar asked Apr 16 '18 06:04

user9040429


People also ask

How does angular implement cookies?

To save information in the cookies you will need to use set() function. It takes two parameters: the name of the key and the value of the key. The get() function is used to get a single value from a cookie. To get all values, you can use the getAll() function.

What is used to read or write a cookie by Angular JS?

AngularJS uses ngCookies module and $cookieStoreservice to carry out the various functions of reading, writing and removing Cookies. The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.

What is NGX cookie service?

Angular service to read, set and delete browser cookies. Originally based on the ng2-cookies library. The experienced team behind Studytube will take care of our cookie service from now on.


1 Answers

I know it's a bit late to answer this but you can use ngx-cookie-service node package for it.

1. Install

npm install ngx-cookie-service --save

2. Then add the cookie service to your app.module.ts as a provider:

@NgModule({
  ...,
  providers: [ CookieService ]
})

3. Then, import and inject it into a component:

import { CookieService } from 'ngx-cookie-service';

constructor( private cookieService: CookieService ) { }

  ngOnInit(): void {
    this.cookieService.set( 'Test', 'Hello World' );
    this.cookieValue = this.cookieService.get('Test');
  }

4. You are all set

like image 154
CodeWarrior Avatar answered Oct 07 '22 18:10

CodeWarrior