angularcookiesangular-cookies

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.


Solution

  • 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