Spread the love

This article will give you the understanding of set and get cookies in angular. Cookies are used to store the data in client computer, Cookie can hold tiny information in computer and can retrieve when required for same website.

Cookies can store key value in client system and its send back the cookies with every request so server can identify the user or session.

Why cookies are useful ?

Cookies are very useful for every website because without cookies server will unable to maintain the session for a request response. For example when we make a request to a website server, server sent response to user and the close the connection so here for next request server doesn’t know about the request is from same browser or client or it’s from different client. Therefore here cookies play the role to send some information by which server can identify it’s from same browser.

If you look at server side languages each language creates its own cookie to create the session as below

Cookies

In this tutorial we will learn to create cookies by two methods

  1. Using native javascript way
  2. Using the third party package of angular

So let’s start set and get cookies in angular in native javascript

Step 1 : Create an angular app

First step is to setup an angular app using below command

ng new example-app

Step 2: Create a service

Create a service so we can use it across the components

ng g s Cookie 

this will create a file as below in app directory and add the service in app module

Here is the code for Cookie service

import { Injectable } from '@angular/core';

@Injectable()
export class CookieService {
  constructor() {}

  public getCookie(name: string) {
    let ca: Array<string> = document.cookie.split(';');
    console.log(document.cookie);
    let caLen: number = ca.length;
    let cookieName = `${name}=`;
    let c: string;

    for (let i: number = 0; i < caLen; i += 1) {
      c = ca[i].replace(/^\s+/g, '');
      if (c.indexOf(cookieName) == 0) {
        return c.substring(cookieName.length, c.length);
      }
    }
    return '';
  }

  public deleteCookie(cookieName) {
    this.setCookie({ name: cookieName, value: '', expireDays: -1 });
  }

  /**
   * Expires default 1 day
   * If params.session is set and true expires is not added
   * If params.path is not set or value is not greater than 0 its default value will be root "/"
   * Secure flag can be activated only with https implemented
   * Examples of usage:
   * {service instance}.setCookie({name:'token',value:'abcd12345', session:true }); <- This cookie will not expire
   * {service instance}.setCookie({name:'userName',value:'John Doe', secure:true }); <- If page is not https then secure will not apply
   * {service instance}.setCookie({name:'niceCar', value:'red', expireDays:10 }); <- For all this examples if path is not provided default will be root
   */
  public setCookie(params: any) {
    let d: Date = new Date();
    d.setTime(
      d.getTime() +
        (params.expireDays ? params.expireDays : 1) * 24 * 60 * 60 * 1000
    );
    document.cookie =
      (params.name ? params.name : '') +
      '=' +
      (params.value ? params.value : '') +
      ';' +
      (params.session && params.session == true
        ? ''
        : 'expires=' + d.toUTCString() + ';') +
      'path=' +
      (params.path && params.path.length > 0 ? params.path : '/') +
      ';' +
      (location.protocol === 'https:' && params.secure && params.secure == true
        ? 'secure'
        : '');
  }
}

Step 3: Add components and inject service

Now, create two components one for set the cookie and other for get the cookie in different pages

ng g c SetCookieExample

This will create a folder in app directory named with set-cookie-example and here is component file

import { Component, OnInit } from '@angular/core';
import { CookieService } from '../cookie.service';

@Component({
  selector: 'app-set-cookie-example',
  templateUrl: './set-cookie-example.component.html',
  styleUrls: ['./set-cookie-example.component.css'],
})
export class SetCookieExampleComponent implements OnInit {
  constructor(public cookie: CookieService) {}

  ngOnInit() {
    this.cookie.setCookie({
      name: 'user',
      value: 'Readerstack',
      session: true,
    });
  }
}

here we injected the Cookie service and then set user cookie in browser

this.cookie.setCookie({
      name: 'user',
      value: 'Readerstack',
      session: true,
    });

Html to link to another page

<p>We have set cookies on this page</p>
<a routerLink="get-cookie">Get cookie another page</a>

Create another component to get the cookies

ng g c GetCookieExample

This will create a folder in app directory named with get-cookie-example and here is component file

import { Component, OnInit } from '@angular/core';
import { CookieService } from '../cookie.service';

@Component({
  selector: 'app-get-cookie-example',
  templateUrl: './get-cookie-example.component.html',
  styleUrls: ['./get-cookie-example.component.css'],
})
export class GetCookieExampleComponent implements OnInit {
  user: string;

  constructor(public cookie: CookieService) {}

  ngOnInit() {
    this.user = this.cookie.getCookie('user');
  }
}

we fetched the stored value in cookie using this.user = this.cookie.getCookie('user');

Html to display name

<p>Getting cookie on this page</p>
User : {{ user }}

Step 4: Add routes in app routing

Finally add the routes in app.routing.module.ts to test the implementation

import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { SetCookieExampleComponent } from './set-cookie-example/set-cookie-example.component';
import { GetCookieExampleComponent } from './get-cookie-example/get-cookie-example.component';
import { CookieService } from './cookie.service';

@NgModule({
  declarations: [SetCookieExampleComponent, GetCookieExampleComponent],
  imports: [
    BrowserModule,
    RouterModule.forRoot([
      { path: '', component: SetCookieExampleComponent },
      { path: 'get-cookie', component: GetCookieExampleComponent },
    ]),
  ],
  exports: [RouterModule],
  providers: [CookieService],
})
export class AppRoutingModule {}

Also note here we added the Service in app.module.ts file

... 
providers: [CookieService]
....

Run the application and check implementation

Live Demo https://set-and-get-cookies-in-angular-readerstacks.stackblitz.io/

Download Code : https://stackblitz.com/edit/set-and-get-cookies-in-angular-readerstacks

One thought on “How to set and get cookies in angular ?

Leave a Reply