angular - 我们如何在没有 ngx-cookie 服务的情况下访问 Angular 6 中的 cookie

标签 angular cookies ngx-cookie-service

  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>

我想访问 Angular 6 中的 cookie,而不需要像 ng-x cookie 服务这样的外部模块。我想使用 get set 删除。有什么方法吗?我已经完成了像 document.cookie 这样的 javascript 方法,但它抛出错误

最佳答案

您可以使用以下方法将文档注入(inject)到您的组件/服务中:

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-service。如果您不想,可以将这些功能添加到您的组件中:

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' );
  }
}

关于angular - 我们如何在没有 ngx-cookie 服务的情况下访问 Angular 6 中的 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54380886/

相关文章:

angular - NGX Cookie 服务不返回任何内容

regex - 无效的正则表达式组 javascript

angular - angular 2 和纯 javascript 之间的通信

html - 遍历元素列表,在悬停时显示分配的图像

angular - ng-cli 不会将组件添加到应用程序模块

java - 如何在 android.webkit.WebView(s) 之间共享缓存,包括 cookie

javascript - Rails 6 与 js-cookie 库 : cookie is set but not persistent

javascript - 我需要从浏览器中获取所有 cookie