как мы можем получить доступ к куки в angular 6 без сервиса ngx- cookie - PullRequest
0 голосов
/ 26 января 2019

  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>

Я хочу получить доступ к файлам cookie в формате angular 6 без внешнего модуля, такого как служба cookie ng-x. Я хотел использовать get set delete. есть ли способ? Я сделал с подходом javascript как document.cookie, но его ошибка броска

Ответы [ 2 ]

0 голосов
/ 18 мая 2019

Реализовано с использованием объекта документа браузера.

// 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}`;

Однако для реализации рендеринга на стороне сервера (Angular Universal) не следует использовать объект документа браузера по умолчанию. В этом случае ngx-cookiee поможет.

0 голосов
/ 26 января 2019

Вы можете внедрить документ в свой компонент / сервис, используя:

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) {}
}

И позже вы можете получить к нему доступ, используя

this.document.cookie

Вы просили в комментариях получить удаление набора,но я бы все же рекомендовал использовать ngx-cookie-сервис.Вы можете добавить эти функции в свой компонент, если не хотите:

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' );
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...