3

  login() : any {
    for(let data of this.loginsdata)
    if(this.username == data.usr && this.password == data.pw){
      // this.toastr.success('logged in');
      console.log(this.username);
      console.log(this.password);
      
      this.router.navigate(['table']);
      
    }
    document.cookie =?
  <script type="text/javascript" src="typescript.compile.min.js"></script>

I want to access a cookies in angular 6 without external module like ng-x cookie service. I wanted to use get set delete. is there any method? I have done with javascript approach like document.cookie but its throwing error

Pavan Jadda
  • 4,306
  • 9
  • 47
  • 79
Akhil Raghav
  • 313
  • 1
  • 4
  • 16

2 Answers2

7

You can inject the document into your component/service using:

import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(@Inject(DOCUMENT) private document: Document) {}
}

And you can later access it using

this.document.cookie

You asked in the comments for get set delete, but I'd still recommend using ngx-cookie-service. You may add these functions to your component if you don't want to:

import { Inject, PLATFORM_ID, InjectionToken, Component } from '@angular/core';
import { DOCUMENT, isPlatformBrowser } from '@angular/common';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private readonly documentIsAccessible: boolean;

  constructor(
    @Inject( DOCUMENT ) private document: any,
    @Inject( PLATFORM_ID ) private platformId: InjectionToken<Object>,
  ) {
    this.documentIsAccessible = isPlatformBrowser( this.platformId );
  }

  check( name: string ): boolean {
    if ( !this.documentIsAccessible ) {
      return false;
    }

    name = encodeURIComponent( name );

    const regExp: RegExp = this.getCookieRegExp( name );
    const exists: boolean = regExp.test( this.document.cookie );

    return exists;
  }

  get( name: string ): string {
    if ( this.documentIsAccessible && this.check( name ) ) {
      name = encodeURIComponent( name );

      const regExp: RegExp = this.getCookieRegExp( name );
      const result: RegExpExecArray = regExp.exec( this.document.cookie );

      return decodeURIComponent( result[ 1 ] );
    } else {
      return '';
    }
  }

  getAll(): {} {
    if ( !this.documentIsAccessible ) {
      return {};
    }

    const cookies: {} = {};
    const document: any = this.document;

    if ( document.cookie && document.cookie !== '' ) {
      const split: Array<string> = document.cookie.split(';');

      for ( let i = 0; i < split.length; i += 1 ) {
        const currentCookie: Array<string> = split[ i ].split('=');

        currentCookie[ 0 ] = currentCookie[ 0 ].replace( /^ /, '' );
        cookies[ decodeURIComponent( currentCookie[ 0 ] ) ] = decodeURIComponent( currentCookie[ 1 ] );
      }
    }

    return cookies;
  }

  set(
    name: string,
    value: string,
    expires?: number | Date,
    path?: string,
    domain?: string,
    secure?: boolean,
    sameSite?: 'Lax' | 'Strict'
  ): void {
    if ( !this.documentIsAccessible ) {
      return;
    }

    let cookieString: string = encodeURIComponent( name ) + '=' + encodeURIComponent( value ) + ';';

    if ( expires ) {
      if ( typeof expires === 'number' ) {
        const dateExpires: Date = new Date( new Date().getTime() + expires * 1000 * 60 * 60 * 24 );

        cookieString += 'expires=' + dateExpires.toUTCString() + ';';
      } else {
        cookieString += 'expires=' + expires.toUTCString() + ';';
      }
    }

    if ( path ) {
      cookieString += 'path=' + path + ';';
    }

    if ( domain ) {
      cookieString += 'domain=' + domain + ';';
    }

    if ( secure ) {
      cookieString += 'secure;';
    }

    if ( sameSite ) {
      cookieString += 'sameSite=' + sameSite + ';';
    }

    this.document.cookie = cookieString;
  }

  delete( name: string, path?: string, domain?: string ): void {
    if ( !this.documentIsAccessible ) {
      return;
    }

    this.set( name, '', new Date('Thu, 01 Jan 1970 00:00:01 GMT'), path, domain );
  }

  deleteAll( path?: string, domain?: string ): void {
    if ( !this.documentIsAccessible ) {
      return;
    }

    const cookies: any = this.getAll();

    for ( const cookieName in cookies ) {
      if ( cookies.hasOwnProperty( cookieName ) ) {
        this.delete( cookieName, path, domain );
      }
    }
  }

  private getCookieRegExp( name: string ): RegExp {
    const escapedName: string = name.replace( /([\[\]\{\}\(\)\|\=\;\+\?\,\.\*\^\$])/ig, '\\$1' );

    return new RegExp( '(?:^' + escapedName + '|;\\s*' + escapedName + ')=(.*?)(?:;|$)', 'g' );
  }
}
Zoltán Szepesi
  • 501
  • 5
  • 10
  • how can set , get and delete cookies its like javascript or different method suggest me – Akhil Raghav Jan 27 '19 at 04:29
  • For that, you have to use a library. If you don't want to use anything else you have to implement it yourself. You just have to parse the cookie string and create your own get set and delete methods. There are not built in functions like this. – Zoltán Szepesi Jan 27 '19 at 11:23
  • @AkhilRaghav I've edited my answer with some example commands – Zoltán Szepesi Jan 27 '19 at 12:38
  • I want in terms of examples so that i can understand clearly I have seen some methods But unable to understand it – Akhil Raghav Jan 27 '19 at 12:38
  • Cookies are stored in a string in the browser with `;` between them. And they are a key value pair with `=` between them. You just have to split the string if you want to get the value by the semicolon first and then by the `=`. If you'd like to add a value to it just append a semicolon to the end, and then print your cookie in a `key=value` format. – Zoltán Szepesi Jan 27 '19 at 12:41
  • And to delete a cookie you just simply make the expiration date to a date in the past – Zoltán Szepesi Jan 27 '19 at 12:42
  • In this case, if you'd like to add a cookie with a name `test` and a value `value` you use this code somewhere with `this.set('test', 'value)`. The arguments with a `?` after them are all optional. You don't have to specify them. – Zoltán Szepesi Jan 27 '19 at 12:44
  • Sir,I am beginner I want to learn without external modules so I asked this question I have posted my code Can you please check it out refer me good solution – Akhil Raghav Jan 27 '19 at 13:01
  • Actually you're using AngularJS 1.6 which is NOT the same as Angular 6. I recommend you to go to the [Angular Quick Start Guide](https://angular.io/guide/quickstart) to start using the latest Angular. – Zoltán Szepesi Jan 27 '19 at 13:06
  • Also, don't be afraid to use external libraries in development. They are available for a reason and you don't have to reinvent the wheel every time you write something. – Zoltán Szepesi Jan 27 '19 at 13:08
  • Given the code you wrote I assume you currently don't really understand how the web works. That is not a problem, everyone has to start somewhere. I would recommend you to take some online courses for example complete the [freeCodeCamp](https://freecodecamp.org) tutorials before building your own websites. – Zoltán Szepesi Jan 27 '19 at 13:19
  • I am using angular 6 and typescript yes i understood how to use cookies in angular but I wanted to know detailed information about it so I choose it – Akhil Raghav Jan 27 '19 at 13:30
2

Implemented using browser's document object.

// Set Cookiee
// "Secure;HttpOnly;" will work if your site is having SSL certificate.
// You can ignore these 2 attributes in development.
document.cookie = `myKey=${myValue};Path=/;Secure;HttpOnly;`;

// Read Cookiee
const _name = 'myKey',
let value = `; ${document.cookie}`.match(`;\\s*${_name}=([^;]+)`);

// Delete Cookiee (using expiration time)
const expires = 'expires=' + new Date().toUTCString();
document.cookie = `myKey=;Path=/;expires=${expires}`;

However, for Server Side Rendering (Angular Universal) implementation, you should not use default browser document object. In that case, ngx-cookiee will help.

Prateek Kumar Dalbehera
  • 2,194
  • 3
  • 24
  • 30