Giter Site home page Giter Site logo

stevermeister / ngx-cookie-service Goto Github PK

View Code? Open in Web Editor NEW
518.0 15.0 87.0 2.89 MB

Angular (4.2+ ...12) service for cookies. Originally based on the `ng2-cookies` library.

Home Page: https://www.npmjs.com/package/ngx-cookie-service

License: MIT License

TypeScript 100.00%
typescript angular angular2 aot ngx cookie cookies cookie-service angular-service ng

ngx-cookie-service's Introduction

NGX Cookie Service

Build npm bundle size Ngx Cookie Service on npm Chat in Gitter ngx-cookie-service channel on discord

Angular service to read, set and delete browser cookies. Originally based on the ng2-cookies library. This service is lightweight, and its bundle size is 1.3 Kb to ensure fast loading times and optimal performance.

Installation

npm i ngx-cookie-service

# or

yarn add ngx-cookie-service

Demo

https://stackblitz.com/~/github.com/pavankjadda/ngx-cookie-service-demo

Usage

  1. In standalone components, import the CookieService directly into the component

    import { CookieService } from 'ngx-cookie-service';
    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-component',
      template: `<h1>Hello World</h1>`,
      providers: [CookieService],
    })
    export class HelloComponent {
      constructor(private cookieService: CookieService) {
        this.cookieService.set('token', 'Hello World');
        console.log(this.cookieService.get('token'));
      }
    }
  2. You can also use inject() method in v14+ to inject the service into the component

    import { CookieService } from 'ngx-cookie-service';
    import { Component, inject } from '@angular/core';
    
    @Component({
      selector: 'my-component',
      template: `<h1>Hello World</h1>`,
      providers: [CookieService],
    })
    export class HelloComponent {
      cookieService = inject(CookieService);
    
      constructor() {
        this.cookieService.set('token', 'Hello World');
        console.log(this.cookieService.get('token'));
      }
    }

Server Side Rendering

Ngx Cookie Service supports Server Side Rendering (SSR) via dedicated library ngx-cookie-service-ssr. Only install ngx-cookie-service-ssr library (and skip ngx-cookie-service) for SSR

  1. Install the library using below command

        npm install ngx-cookie-service-ssr --save
    
        # or
    
        yarn add ngx-cookie-service-ssr
  2. By default, browser cookies are not available in SSR because document object is not available. To overcome this, navigate to server.ts file in your SSR project, and replace the following code

    server.get('*', (req, res) => {
      res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
    });

with this

import { REQUEST as SSR_REQUEST } from "ngx-cookie-service-ssr";

server.get('*', (req, res) => {
  res.render(indexHtml, {
    req,
    providers: [
      { provide: APP_BASE_HREF, useValue: req.baseUrl },
      { provide: SSR_REQUEST, useValue: req },
      { provide: 'RESPONSE', useValue: res },
    ],
  });
});
  1. This will make sure the cookies are available in REQUEST object, and the ngx-cookie-service-ssr can use REQUEST.cookies to access the cookies in SSR. Then proceed to use ngx-cookie-service as usual.
  2. See the sample repo for more details.

Supported Versions

We follow angular LTS versions. The latest version of the library supports Angular 17.x.x. Angular 14.x.x or below is not supported.

Angular Version Supported Version
17.x.x 17.x.x
16.x.x 16.x.x
15.x.x 15.x.x

API

check( name: string ): boolean;

const cookieExists: boolean = cookieService.check('test');

Checks if a cookie with the givenname can be accessed or found.

get( name: string ): string;

const value: string = cookieService.get('test');

Gets the value of the cookie with the specified name.

getAll(): {};

const allCookies: {} = cookieService.getAll();

Returns a map of key-value pairs for cookies that can be accessed.

set( name: string, value: string, expires?: number | Date, path?: string, domain?: string, secure?: boolean, sameSite?: 'Lax' | 'Strict' | 'None' ): void;

set( name: string, value: string, options?: { expires?: number | Date, path?: string, domain?: string, secure?: boolean, sameSite?: 'Lax' | 'None' | 'Strict'}): void;

cookieService.set('test', 'Hello World');
cookieService.set('test', 'Hello World', { expires: 2, sameSite: 'Lax' });

Sets a cookie with the specified name and value. It is good practice to specify a path. If you are unsure about the path value, use '/'. If no path or domain is explicitly defined, the current location is assumed. sameSite defaults to Lax.

Important: For security reasons, it is not possible to define cookies for other domains. Browsers do not allow this. Read this and this StackOverflow answer for a more in-depth explanation.

Important: Browsers do not accept cookies flagged sameSite = 'None' if secure flag isn't set as well. CookieService will override the secure flag to true if sameSite='None'.

delete( name: string, path?: string, domain?: string, secure?: boolean, sameSite: 'Lax' | 'None' | 'Strict' = 'Lax'): void;

cookieService.delete('test');

Deletes a cookie with the specified name. It is best practice to always define a path. If you are unsure about the path value, use '/'.

Important: For security reasons, it is not possible to delete cookies for other domains. Browsers do not allow this. Read this and this StackOverflow answer for a more in-depth explanation.

deleteAll( path?: string, domain?: string, secure?: boolean, sameSite: 'Lax' | 'None' | 'Strict' = 'Lax' ): void;

cookieService.deleteAll();

Deletes all cookies that can currently be accessed. It is best practice to always define a path. If you are unsure about the path value, use '/'.

FAQ

General tips

Checking out the following resources usually solves most of the problems people seem to have with this cookie service:

The following general steps are usually very helpful when debugging problems with this cookie service or cookies in general:

I am always getting a "token missing" or "no provider" error.

Package managers are a well known source of frustration. If you have "token missing" or "no provider" errors, a simple re-installation of your node modules might suffice:

rm -rf node_modules
yarn # or `npm install`

I have a problem with framework X or library Y. What can I do?

Please be aware that we cannot help you with problems that are out of scope. For example, we cannot debug a Symfony or Springboot application for you. In that case, you are better off asking the nice folks over at StackOverflow for help.

Do you support Angular Universal?

There is an issue for that. Check out this comment for more information about future support.

Opening issues

Please make sure to check out our FAQ before you open a new issue. Also, try to give us as much information as you can when you open an issue. Maybe you can even supply a test environment or test cases, if necessary?

Contributing

We are happy to accept pull requests or test cases for things that do not work. Feel free to submit one of those.

However, we will only accept pull requests that pass all tests and include some new ones (as long as it makes sense to add them, of course).

Author

This cookie service is brought to you by 7leads GmbH. We built it for one of our apps, because the other cookie packages we found were either not designed "the Angular way" or caused trouble during AOT compilation.

Contributors

Thanks to all contributors:

License

MIT

ngx-cookie-service's People

Contributors

andreas-aeschlimann avatar cunningfatalist avatar dbaker85 avatar dependabot[bot] avatar flakolefluk avatar icebreakerg avatar leomendoza123 avatar mattbanks avatar mattlewis92 avatar mhartkorn avatar minijus avatar nikel163 avatar pavankjadda avatar rojedalopez avatar shaozi avatar stevermeister avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ngx-cookie-service's Issues

Http Interceptor

Hi. I have a problem in my authentication. I have attached the http interceptor in every request i make. I have a problem in logging in of my application. I am not able to login since i have this error in my code
capture

These are my codes

onSignIn() {
    const formData = {
      email: this.loginForm.get('email').value,
      password: this.loginForm.get('password').value
    };
    if (this.loginForm.valid) {
      this.authService.signinUser(formData)
      .subscribe(
        data => {
          console.log(data);
          this.cookieService.set('auth_token', data.token);
          console.log(data);
        },
        error => {
          console.log(error);
        });
    }
  }
`@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  private authService: AuthService;

  constructor(private injector: Injector, private router: Router, private cookieService: CookieService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    // Get the auth header from the service.
    this.authService = this.injector.get(AuthService);
    const token: string = this.cookieService.get('auth_token');
    const role: string = this.authService.getRole();
    const corp: string = this.cookieService.get('corp_id');
    const dept: string = this.cookieService.get('dept_id');
    const user = this.cookieService.get('user_id');

    if (role !== null) {
      req = req.clone({ headers: req.headers.set('role' ? 'role' : null , role ? role : null) });
    }

    if (corp !== null) {
      req = req.clone({ headers: req.headers.set('corp-id' ? 'corp-id' : null , corp ? corp : null) });
    }

    if (dept !== null) {
      req = req.clone({ headers: req.headers.set('dept-id' ? 'dept-id' : null , dept ? dept : null) });
    }

    if (user !== null) {
      req = req.clone({ headers: req.headers.set('user-id' ? 'user-id' : null , user ? user : null) });
    }

    if (token) {
      req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
    }

    if (!req.headers.has('Content-Type')) {
      req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
    }

    req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
    return next.handle(req).do(
      (event: HttpEvent<any>) => {},
      (err: any) => {
        if (err instanceof HttpErrorResponse) {
          if (err.status === 401 || err.status === 403 || err.status === 400 ) {
            swal('Session Expired!", "Sorry, your session has expired, you will be redirected to the login page", "warning');
            this.authService.logout();
          }
          if (err.status === 500 || err.status === 0 ) {
            this.router.navigate(['error'])
          }
        }
      }
      )
  }`

`export class AuthService {
  token: string;

  constructor(private httpClient: HttpClient, private router: Router, private cookieService: CookieService) {}

  signinUser(formData) {
    return this.httpClient
    .post(
       `${environment.url}/auth/login`,
       JSON.stringify(formData)
    )
    .map((response: any) => {
         return response;
        });
  }

  logout(): void {
    localStorage.clear();
    this.router.navigate(['login']);
  }

  setSession(token: string): void {
    this.cookieService.set('auth_token', JSON.stringify(token));
  }

  isLoggedIn(): boolean {
    const token = this.getToken();
    if (!token) {
      return false;
    }
    return true;
  }

  getToken(): string {
    return this.cookieService.get('auth_token');
  }

  getRole() {
    return this.cookieService.get('user_role');
  }

  getCorp() {
    return this.cookieService.get('corp_id')
  }

  getDept() {
    return this.cookieService.get('dept_id')
  }

  getUserID() {
    return this.cookieService.get('user_id')
  }`

Cookies don't show up if domain attribute has 2 (or more?) subdomain levels

This issue occurs when the domain attribute of a received cookie has 2 (or more, I assume) subdomain levels (e.g. myCookie=myValue; domain=my.subdomain.domain.com; path=/).

Expected Behavior

cookieService.get('myCookie') or cookieService.getAll() return the cookies.

Actual Behavior

cookieService.get('myCookie') return an empty string, and cookieService.getAll() is empty.

Steps to Reproduce the Problem

Use ngx-cookie-service to retrieve a cookie that has a domain attribute with 2 (maybe more as well, I didn't test with more than 2) subdomain levels.

Specifications

  • Version: ngx-cookie-service 1.0.10
  • Browser: Chrome 71.0.3578.98

Unexpected token export

Expected Behavior

should work during build in angular universal env
...

Actual Behavior

in .../node_modules\ngx-cookie-service\index.js:1
(function (exports, require, module, __filename, __dirname) { export * from './cookie-service/cookie.service';
throwing SyntaxError: Unexpected token export
...

Steps to Reproduce the Problem

...

Specifications

Angular-Universal-App

  • Version: ... 5.2.0

Universal Support

Hy guys,

great module! Are you planning to implement a way to use the module also on the server side.

So that the cookies are read from the intial request captured by node?

Help wanted

Expected Behavior

I want to read cookies from different domain

Actual Behavior

... N/A

Steps to Reproduce the Problem

... N/A

Specifications

  • Version: ...
  • Browser: ...
  • ...

getAll() returns an empty object, even though there are cookies present.

Expected Behavior

this.cookieService.getAll() should return the cookies that are locally stored.
The cookies are set from my server via passport and session.

Actual Behavior

this.cookieService.getAll() returns {}

Steps to Reproduce the Problem

call .getAll() method on the cookie service.

Specifications

  • Version: ^1.0.10
  • Browser: Chrome 64.0.3282.186 (Official Build) (64-bit)

Here are some screenshots and code snippets:


 getAllCookies() {
    console.log(this.cookieService.getAll()); //returns an empty object {}
  }
<button (click)="getAllCookies()">getAllCookies</button>


Proof that I have cookies stored:

http://prntscr.com/ijv4cs < the cookies

http://prntscr.com/ijv4pv < when I click getAll().

Is this a problem on my side, or this issue is valid?

Thanks.

CSRF token not appending

Expected Behavior

CSRF token is added to Request header (POST) except login

Actual Behavior

CSRF roken is not appending in request header.But it sending empty value

Steps to Reproduce the Problem

Use Angular 4+,Django 2.7.6 try to hit from your local machine

Specifications

  • Version:Version 63.0.3239.84 (Official Build) (64-bit)

  • Browser: Chrome
    I attached some screen shot for your reference as well as code i try to fetch csrf and append.

[https://www.codingforentrepreneurs.com/blog/jwt-token-interceptor-for-http-angular/
giterror
git

](url)
Thank you in advance

Cannot read property

When i'm injecting the cookieService to another service it gets an error like this when requesting an http method
screen shot 2017-11-21 at 6 54 20 am

This is my code

import { Injectable } from '@angular/core';
import { Http, Response } from "@angular/http";

import { Observable } from "rxjs/Rx";
import { tokenNotExpired } from 'angular2-jwt';
import { UtilService } from "../services";
import { CookieService } from 'ngx-cookie-service';

@Injectable()
export class AuthService {
  Http;

  static parameters = [Http];
  constructor (
    private http: Http,
    private util: UtilService,
    private _cookieService: CookieService
  ) {
    this.Http = http;
  }

  // authenticates the user
  authenticate(data) {
    console.log(this._cookieService.get('company'), 'hereree')
    var body = {
      email: data.username,
      password: data.password,
      // company_slug: this._cookieService('company').get || ''
    }

    return this.Http.post('/api/users/session', body)
    .map((data: Response) => data.json())
    .catch(this.handleError);;
  }

  // check if the user's token is not expired
  loggedIn(token) {
    return tokenNotExpired(null, token);
  }

  // Remove the user's data
  logout() {
    this.util.deleteAllCookieData()
  }

  private handleError (error: any) {
    return Observable.throw(error.json());
  }
}

still compatible ?

Correct me if I'm wrong, but this service is not compatible with the latest angular versions is it ?

I am having the following errors:

Uncaught Error: Can't resolve all parameters for CookieService: (?, [object Object])

Which seems to make perfect sense, because indeed, if you look at the signature of the constructor of this service, it does take 2 parameters. And I have no idea where this information should come from.

Then secondly, there is the following error, (possibly related to the previous one):

/~/ngx-cookie-service/cookie-service/cookie.service.js 145:59-67 "export 'DOCUMENT' was not found in '@angular/common'

That seems to imply that something has changed in the @angular/common libs, right ?

At first I was running on angular 4, and now just upgraded to angular 7.
I had the exact same error messages with both versions.

Update version dependency/README.md

Expected Behavior

To import CookieService

Actual Behavior

Cannot find DOCUMENT from angular/common

Steps to Reproduce the Problem

Take the specific Angular version: < 4.3.0

Specifications

  • Version: 4.2.5
  • Browser: -
  • ...

You should update your version dependency/README.md, import DOCUMENT from angular/common works only with Angular version >= 4.3.0

This module does not work with `ng test`

Expected Behavior

Test Pass

Actual Behavior

Error Unexpected token import

Steps to Reproduce the Problem

Run ng test on a component you are trying to test which uses this library

Specifications

  • Version: Angular 5
  • Browser: N/A

Springboot JSESSIONID in auth service

Expected Behavior

check JSESSIONID cookie

Actual Behavior

returns false even though the cookie exists

Steps to Reproduce the Problem

I am trying to setup an Auth service to check if a JSESSIONID cookie exists or has been created by Springboot. My service looks like this:

import { Injectable } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';

@Injectable()
export class AuthService {

    constructor(
        private cookieService: CookieService
    ) {}

    get isLoggedIn() {
        this.cookieService.set( 'test', 'Hello World' );
        const jsession = this.cookieService.check('JSESSIONID');
        console.log(jsession);
        if (!jsession) {
            return false;
        } else {
            return true;
        }
    }

    get isAdmin() {
        return true;
    }

    get isManager() {
        return false;
    }

    get userLang() {
        return 'en';
    }

}

I am able to confirm that the session cookie does in fact exist, however neither const jsession = this.cookieService.check('JSESSIONID');, getAll(), or get() seem to see the cookie?

Cookies not deleting all the time

The delete() and the deleteAll() functions does not delete the cookies everytime. Sometimes its working, but sometimes it not deleting the cookies. Can you please confirm if this instability still exists.

How to get ALL cookies from browser for current domain?

I used the latest version of the service and tried to get all cookies that I see in browser's request. While my backend sends several cookies, I see just a few of them. How can I extract all cookies, not only those I set via set() method?

How to set the cookie as an array cookie and keep on updating the array.

I was able to set the cookie.I need to set the cookie as an array and want to keep updating that array.

Use Case:I have videos in my platform and I want to capture the watched video for not logged in
user.So each time user watches the video I want to update the cookie array with video ID ,so that
when the same user visit my site next time , I will know what are the video which has been
watched by that particular user.

Can't resolve '@angular/common'

ERROR in ../node_modules/ngx-cookie-service/cookie-service/cookie.service.js
Module not found: Error: Can't resolve '@angular/common' in '/var/www/html/staffplan/node_modules/ngx-cookie-service/cookie-service'

Angular Universal SSR rendering problem

ERROR Error: NotYetImplemented is the error I got and it mentioned something such as "at CookieService.check" and "at CookieService.get". How can I fix it?

skip encodeURIComponent for cookie name and value

Expected Behavior

...
this package automatically encode the string which i set

Actual Behavior

...

Steps to Reproduce the Problem

...
how to skip this encoding

Specifications

  • Version: ...
  • Browser: ...
  • ...

Error: No Exported member Opaque Token.

I have updated my angular version 4 to 5 . Have got an issue with ngx-cookie npm module. Becase of that I am now trying to install ngx-cookie-service module which gives me the same error.
Below is my package.json and the error.
Can someone please help me out as it is urgent. Thank you !

Error:

ERROR in node_modules/@rewardle/core/node_modules/ngx-cookie/src/cookie-options-provider.d.ts(1,20): error TS2305: Module '"C:/Users/Developer1/Tarunprojects/angularportals/rewardle.boilerplate.portal/node_modules/@angular/core/core"' has no exported member 'OpaqueToken'.

My Package.json:

{
"name": "rewardle.boilerplate.portal",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test --browsers=Chrome",
"test:ci": "ng test --browsers=Headless_Chrome --code-coverage=true --single-run=true",
"lint": "ng lint --type-check",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "^5.0.0",
"@angular/common": "^5.0.0",
"@angular/compiler": "^5.0.0",
"@angular/core": "^5.0.0",
"@angular/forms": "^5.0.0",
"@angular/http": "^5.0.0",
"@angular/platform-browser": "^5.0.0",
"@angular/platform-browser-dynamic": "^5.0.0",
"@angular/platform-server": "^5.0.0",
"@angular/router": "^5.0.0",
"@rewardle/core": "1.6.159",
"angular-in-memory-web-api": "^0.3.1",
"angular2-materialize": "^6.7.2",
"angular2-moment": "^1.4.0",
"core-js": "^2.4.1",
"hammerjs": "^2.0.8",
"jquery": "^2.2.4",
"json-typescript-mapper": "^1.1.3",
"materialize-css": "^0.98.2",
"moment": "^2.18.1",
"ng-pick-datetime": "^4.2.3",
"ng2-completer": "^1.5.2",
"ngx-cookie-service": "1.0.10",
"ngx-papaparse": "^1.2.2",
"reflect-metadata": "^0.1.10",
"rxjs": "^5.5.2",
"zone.js": "^0.7.8"
},
"devDependencies": {
"@angular/cli": "^1.6.6",
"@angular/compiler-cli": "^5.0.0",
"@types/jasmine": "2.5.38",
"@types/node": "^7.0.12",
"codelyzer": "^3.1.2",
"jasmine-core": "~2.5.2",
"jasmine-spec-reporter": "~3.2.0",
"karma": "~1.4.1",
"karma-chrome-launcher": "~2.2.0",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^0.2.0",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.1.0",
"ts-node": "^3.0.2",
"tslint": "^5.0.0",
"typescript": "2.4.2"
}
}

Adding ngx-cookie-service broke Jest tests

Expected Behavior

Dependency should import correctly and operate normally during test runs

Actual Behavior

ttucker:rac-web-admin thomastucker$ yarn test
yarn run v1.9.2
$ jest
PASS src/app/auth/reducers/auth.reducer.spec.ts
AuthReducer
undefined action
✓ should return the default state (9ms)
LOGIN_SUCCESS
✓ should add a user set loggedIn to true in auth state (1ms)
LOGOUT
✓ should logout a user (1ms)

PASS src/app/+promotions/containers/add-promotion-page/add-promotion-page.component.spec.ts
AddPromotionPageComponent
✓ should create (120ms)

PASS src/app/core/containers/page-not-found/page-not-found.component.spec.ts
PageNotFoundComponent
✓ should create (116ms)

PASS src/app/core/containers/app/app.component.spec.ts
AppComponent
✓ should create (120ms)

PASS src/app/core/components/header/header.component.spec.ts
HeaderComponent
✓ should create (185ms)

PASS src/app/core/components/sidenav/sidenav.component.spec.ts
SidenavComponent
✓ should create (234ms)

FAIL src/app/app-routing.module.spec.ts
● Test suite failed to run

Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html

Details:

/Users/thomastucker/dev/rac-web-admin/node_modules/ngx-cookie-service/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './cookie-service/cookie.service';
                                                                                         ^^^^^^

SyntaxError: Unexpected token export

  15 | export class AuthGuard implements CanActivate {
  16 |   constructor(
> 17 |     private cookie: CookieService,
     |                            ^
  18 |     private store: Store<fromAuth.State>,
  19 |   ) {}
  20 | 

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
  at Object.<anonymous> (src/app/auth/services/auth-guard.service.ts:17:28)

FAIL src/app/auth/services/auth-guard.service.spec.ts
● Test suite failed to run

Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html

Details:

/Users/thomastucker/dev/rac-web-admin/node_modules/ngx-cookie-service/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './cookie-service/cookie.service';
                                                                                         ^^^^^^

SyntaxError: Unexpected token export

  15 | export class AuthGuard implements CanActivate {
  16 |   constructor(
> 17 |     private cookie: CookieService,
     |                            ^
  18 |     private store: Store<fromAuth.State>,
  19 |   ) {}
  20 | 

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
  at Object.<anonymous> (src/app/auth/services/auth-guard.service.ts:17:28)

FAIL src/app/auth/effects/auth.effects.spec.ts
● Test suite failed to run

Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html

Details:

/Users/thomastucker/dev/rac-web-admin/node_modules/ngx-cookie-service/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './cookie-service/cookie.service';
                                                                                         ^^^^^^

SyntaxError: Unexpected token export

  17 |   @Effect()
  18 |   login$ = this.actions$.pipe(
> 19 |     ofType<AuthActions.Login>(AuthActions.AuthActionTypes.LOGIN),
     |                            ^
  20 |     map(action => action.payload.credentials),
  21 |     flatMap((credentials: Credentials) =>
  22 |       this.authService.login(credentials).pipe(

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
  at Object.<anonymous> (src/app/auth/effects/auth.effects.ts:19:28)

FAIL src/app/+promotions/promotions.module.spec.ts
● Test suite failed to run

Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html

Details:

/Users/thomastucker/dev/rac-web-admin/node_modules/ngx-cookie-service/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './cookie-service/cookie.service';
                                                                                         ^^^^^^

SyntaxError: Unexpected token export

  15 | export class AuthGuard implements CanActivate {
  16 |   constructor(
> 17 |     private cookie: CookieService,
     |                            ^
  18 |     private store: Store<fromAuth.State>,
  19 |   ) {}
  20 | 

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
  at Object.<anonymous> (src/app/auth/services/auth-guard.service.ts:17:28)

PASS src/app/auth/containers/login-page/login-page.component.spec.ts
Login Page
✓ should compile (390ms)

Test Suites: 4 failed, 7 passed, 11 total
Tests: 9 passed, 9 total
Snapshots: 4 passed, 4 total
Time: 3.301s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Steps to Reproduce the Problem

ng create app
add jest https://brianflove.com/2018/05/26/angular-jest-testing/
add ngx-cookie-service
view tests failing

Specifications

  • Version:
    node - v9.4.0
    npm - 5.6.0

  • Browser: ...

  • ...

Intermittant Access to set cookies

Here's an example - Hoping to have some insight into why it may be doing this, whether there is a setting I can change to stop it, but I suspect it is a bug

  1. So I set a few cookies in a login process (sets the cookie fine)
  2. I'm on a URL like /account/settings -> I hit refresh - the cookie doesn't exist
  3. I then navigate to another page -> like /account/XXX/XXX/XXX -> and hit refresh - the cookie re-appears again

I could do a screen cast to show the problem - it is very strange

this.cookieService.delete('TestCookie') is not working

Expected Behavior

I am working on Logout functionality in Angular 7 using ngx-cookie-service. Below is the code of my Logout() function. I am having issue in this.cookieService.delete('Cookie') function.

this.cookieService.delete('TestCookie');
console.log("cookie deleted!");

        if (this.cookieService.get('TestCookie') && this.cookieService.get('TestCookie') != null && this.cookieService.get('TestCookie') != '') {
            console.log("cookie found!");
        }  
        else{   

            console.log("cookie not found!");

            this.commonservice.logout().subscribe(
                data => {
                    if (data.status == 200) {
                        console.log("logout data,",data);      
                    }
                },
                error => {
                    return Observable.throw(error);
                }
            );
            console.log("navigate to login");
            this.router.navigate(['/login']);
        }      
    }

It should print "Cookie deleted" and then it should print "cookie not found!" and then logout method should be called

Actual Behavior

Actually it is behaving as below:
"Cookie deleted! "is printed and then "cookie found" so the user is not logged out .
Even in Application i can see the cookie is remained as it is.

Steps to Reproduce the Problem

please guide me through this problem,Thank you

Specifications

  • Version: Angular 7, ngx-cookie-service : 2.1.0
  • Browser: Chrome

Its only saving one array with two object

this.cookieService.set( 'cart', JSON.stringify(this.addedItems));

var sssl = this.cookieService.get('cart');
sssl = JSON.stringify(sssl);
this.cartItems = JSON.parse(JSON.parse(sssl));
Stored Data Type
(2) [{…}, {…}]

NotYetImplemented in SSR

Actual Behavior

Doesn't work with SSR
Output:

Error: NotYetImplemented
    at Object.module.exports.exports.nyi (/var/task/dist/server.js:25776:9)
    at CookieService.module.exports.CookieService.check (/var/task/dist/server.js:178063:47)
    at CookieService.module.exports.CookieService.get (/var/task/dist/server.js:178071:47)
    at n.e.RehydrateStoreService.n.restore (/var/task/dist/server.js:206494:13762)
    at Iksp.e.getInitialState (/var/task/dist/server.js:206494:979474)
    at _callFactory (/var/task/dist/server.js:11245:20)
    at _createProviderInstance$1 (/var/task/dist/server.js:11197:26)
    at initNgModule (/var/task/dist/server.js:11147:28)
    at new NgModuleRef_ (/var/task/dist/server.js:12390:9)
    at Object.createNgModuleRef (/var/task/dist/server.js:12380:12)

Document in server side has cookie but in get case throw Error: NotYetImplemented
https://github.com/fgnass/domino/blob/master/lib/Document.js#L308

Specifications

Angular 5

Not deleting cookie in dev

Expected Behavior

...
Service should delete the cookie.

Actual Behavior

...
Service doesn't delete the cookie with cookieService.delete("key"); and cookieService.deleteAll();,
I've tried adding the path in the second parameter as well.

Steps to Reproduce the Problem

...

Specifications

  • Version: ..."ngx-cookie-service": "^1.0.10", "@angular/core": "^5.2.0",
  • Browser: ... *
  • ...

Could not resolve ngx-cookie-service ...

Expected Behavior

... no error should be thrown as part of ng build

Actual Behavior

... Could not resolve ngx-cookie-service relative
error TS2307: Cannot find module 'ngx-cookie-service'.
src/app/app.module.ts(22,29): error TS2307: Cannot find module 'ngx-cookie-service'.

Steps to Reproduce the Problem

... install the latest ngx-cookie-service

Specifications

  • Version: ... 2.0.1
  • Browser: ...
  • ...
    I was working perfectly fine until today after updating the package

Delete functionality not working in Safari

Expected Behavior

cookieService.delete('token'); and cookieService.deleteAll('token'); should delete the cookies with name token irrespective of browser.

Actual Behavior

This is working on Chrome but it is not on Safari browser. However, cookieService.deleteAll(); works on both the browsers.

Steps to Reproduce the Problem

I have create a project to reproduce the same on Github.

https://github.com/ahmadimt/ngx-cookie-bug

Specifications

  • ngx-cookie-service Version: 1.0.10
  • Browser: Safari Version 11.1.1 (13605.2.8)

Same Name diff domains.

Expected Behavior

Not to sure.

Actual Behavior

Want to clarify.

Steps to Reproduce the Problem

Make a cookie with id foobar and domain as foo.bar.com, make a cookie with the domain set to bar.com, what would happen in this case? I couldn't seem to find any documentation on this. From my understanding i see a issue in ng-cookie.. not sure if it's related as this library is based off ng2-cookie not ng-cookie.

Specifications

  • Version: N/A
  • Browser: N/A

URI malformed error for cookie value of '20%'

Expected Behavior

  • I don't expect any errors when parsing existing cookies (eg. with a value of 20%)

Scenario

  • I am developing a new website. Users of the existing website have existing cookies already set.
  • Currently a cookie containing the exact value 20% has been set by the old website
  • No I don't mean %20 !
  • I get an error just trying to run getAll()

Actual Behavior

I get URI malformed because decodeURIComponent('20%') fails

Steps to Reproduce the Problem

  • Set cookie value of 20%
  • Try to execute getAll()

Specifications

  • Version: 2.1.0
  • Browser: Chrome

How do I mock this for testing?

How/where do I setup/mock cookies for the cookie service to read? I don't really want to create an entire mock class of my own if I don't have to.

Deleting cookies: All paths & domains

Whe I try to delete a cookie by simple delete method, it does not work. I think it requires to the path & domain also.

this.cookieService.delete("auth_token");

thus, I need to write:

this.cookieService.delete("auth_token", "/", "quizcv.com");
this.cookieService.delete("auth_token", "/", "www.quizcv.com");
this.cookieService.delete("auth_token", "/", "localhost");

which is very uncomfortable. Moreover, there are some combinations with different paths.

How can I delete all cookies, whatever the path or domain is?

NodeInvocationException: StaticInjectorError[CookieService] - No provider for CookieService!

Hi,
I have an ASP.NET Core 2.0 project with an Angular 5.1.0 ClientApp (VS 2017 v15.4.5).
I followed your instructions to import the CookieService, but whenever I try DI it into a component or service constructor I get this error:

NodeInvocationException: StaticInjectorError[CookieService]: 
StaticInjectorError[CookieService]: 
NullInjectorError: No provider for CookieService!
Error: StaticInjectorError[CookieService]: 
StaticInjectorError[CookieService]: 
NullInjectorError: No provider for CookieService!

app.module.browser.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppModuleShared } from './app.module';
import { AppComponent } from './components/app/app.component';
import { HttpModule } from '@angular/http';
import { CookieService } from 'ngx-cookie-service';

@NgModule({
    bootstrap: [AppComponent],
    imports: [BrowserModule, AppModuleShared, HttpModule,FormsModule  
    ],
    providers: [
        {
            provide: 'BASE_URL', useFactory: getBaseUrl
        },
        CookieService 
    ]
})

export class AppModule { }
[...]

component.ts:

[...]
import { CookieService } from 'ngx-cookie-service';

@Component({
    selector: 'setlanguage',
    templateUrl: './setlanguage.component.html'
})
export class SetLanguageComponent {
    public loc = "";
    constructor(private http: Http, @Inject('BASE_URL') private baseUrl: string,
        private _cookieService: CookieService
    ) {
        this.loc = this._cookieService.get('Locale');
}

My packages:

"dependencies": {
    "@angular-devkit/schematics": "0.0.40",
    "@angular/animations": "5.1.0",
    "@angular/common": "5.1.0",
    "@angular/compiler": "5.1.0",
    "@angular/compiler-cli": "5.1.0",
    "@angular/core": "5.1.0",
    "@angular/forms": "5.1.0",
    "@angular/http": "5.1.0",
    "@angular/platform-browser": "5.1.0",
    "@angular/platform-browser-dynamic": "5.1.0",
    "@angular/platform-server": "5.1.0",
    "@angular/router": "5.1.0",
    "@ngtools/webpack": "1.9.0",
    "@schematics/schematics": "0.0.10",
    "@types/webpack-env": "1.13.3",
    "angular2-template-loader": "0.6.2",
    "aspnet-prerendering": "^3.0.1",
    "aspnet-webpack": "^2.0.1",
    "awesome-typescript-loader": "3.4.1",
    "bootstrap": "3.3.7",
    "css": "2.2.1",
    "css-loader": "0.28.4",
    "es6-shim": "0.35.3",
    "event-source-polyfill": "0.0.9",
    "expose-loader": "0.7.3",
    "extract-text-webpack-plugin": "2.1.2",
    "file-loader": "0.11.2",
    "html-loader": "0.4.5",
    "isomorphic-fetch": "2.2.1",
    "jquery": "3.2.1",
    "json-loader": "0.5.4",    
    "ngx-cookie-service": "1.0.9",
    "preboot": "4.5.2",
    "raw-loader": "0.5.1",
    "reflect-metadata": "0.1.10",
    "rxjs": "5.5.5",
    "style-loader": "0.18.2",
    "to-string-loader": "1.1.5",
    "typescript": "2.6.2",
    "url-loader": "0.6.2",
    "webpack": "3.10.0",
    "webpack-hot-middleware": "2.21.0",
    "webpack-merge": "4.1.1",
    "zone.js": "0.8.18"
  },
  "devDependencies": {
    "@types/chai": "4.0.1",
    "@types/jasmine": "2.8.2",
    "chai": "4.1.2",
    "jasmine-core": "2.8.0",
    "karma": "1.7.1",
    "karma-chai": "0.1.0",
    "karma-chrome-launcher": "2.2.0",
    "karma-cli": "1.0.1",
    "karma-jasmine": "1.1.1",
    "karma-webpack": "2.0.6",
    "@angular/cli": "1.6.0"
  }

Could you please advise? Thank you.

Can you explain how to set() method with path only

Expected Behavior

this.cookieService.set(name, value, path)

Actual Behavior

this.cookieService.set(name, value, undefined, path)

Please explain this in real time example I am confuse how to set path in this cookie service

add support for angular universal

Proposed change is to add CookieServiceModule with two static methods forBrowser() and forServer() where each will provide instance based on Document and Request respectively. Provided CookieService will work in the same way in both environments. Above static methods can be used in BrowserAppModule and ServerAppModule respectively providing same interface different implementations.

Can't resolve all parameters for CookieService

Expected Behavior

I have injected userService to the root module but it's making the error.
image 1

Actual Behavior

It should occur no issue.

Steps to Reproduce the Problem

Please take a look at the screenshot.
image 2

Specifications

  • Version:
    ngx-cookie-service: 1.0.10
    Angular: 4.2.5
    ASP.NET MVC framework
    Windows
  • Browser: Google Chrome

Changelog

Since there's no CHANGELOG.md and no releases or tags, where do I find information about changes in release v2?

#node dist/server.js

1 . angular5.1 -SSR
2. node /dist/server.js
3.error
(function (exports, require, module, __filename, __dirname) { export * from './cookie-service/cookie.service';
^^^^^^
SyntaxError: Unexpected token export

Cookies not getting set

Expected Behavior

Cookie being set

Actual Behavior

No cookie being set

Steps to Reproduce the Problem

What i'm trying to do is to store a JWT token in a cookie using following code.
` setCookie(name: string, value: string, encrypt: boolean, days?: number) {
let date = null;
if (days) {
date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
}

    if(encrypt){
        value = btoa(value);
    }

    this.cookie.set(name, value, date, "/", environment.domain, true);
}`

but the cookie is not getting created. I stept into the code of the plugin and no errors happen there.

Specifications

  • Version: Angular 6
  • Host: LocalHost and deployed version

Get a cookie from a defined path

Hi guys!

Great module! It's very useful!

I have a question for you. I'm going to receive a cookie in my application from an external CRM. It could be stored with path and domain. Using your library, I've tried to retrieve it using the "get" method with cookies's name, but I can't get it if it was created with specified path.

Can I retrieve a cookie specifying the path that was used to create the cookie?

Thanks you in advance!

Jose

Metadata version mismatch for module

hello , i am using CookieSevice , first i have installl them by
npm install ngx-cookie --save then import it in Module
then i created cookie backend for fake token generating , now i am getting error below :--

Error: Metadata version mismatch for module F:/edcertsWallet/node_modules/ngx-cookie/index.d.ts, found version 4, expected 3, resolving symbol AppModule in F:/edcertsWallet/src/app/app.module.ts, resolving symbol AppModule in F:/edcertsWallet/src/app/app.module.ts, resolving symbol AppModule in F:/edcertsWallet/src/app/app.module.ts
at syntaxError (F:\edcertsWallet\node_modules@angular\compiler\bundles\compiler.umd.js:1729:34)
at simplifyInContext (F:\edcertsWallet\node_modules@angular\compiler\bundles\compiler.umd.js:25111:23)
at StaticReflector.simplify (F:\edcertsWallet\node_modules@angular\compiler\bundles\compiler.umd.js:25123:13)
at StaticReflector.annotations (F:\edcertsWallet\node_modules@angular\compiler\bundles\compiler.umd.js:24553:41)
at _getNgModuleMetadata (F:\edcertsWallet\node_modules@angular\compiler-cli\src\ngtools_impl.js:138:31)
at _extractLazyRoutesFromStaticModule (F:\edcertsWallet\node_modules@angular\compiler-cli\src\ngtools_impl.js:109:26)
at Object.listLazyRoutesOfModule (F:\edcertsWallet\node_modules@angular\compiler-cli\src\ngtools_impl.js:53:22)
at Function.NgTools_InternalApi_NG_2.listLazyRoutes (F:\edcertsWallet\node_modules@angular\compiler-cli\src\ngtools_api.js:91:39)
at AotPlugin._getLazyRoutesFromNgtools (F:\edcertsWallet\node_modules@ngtools\webpack\src\plugin.js:241:66)
at _donePromise.Promise.resolve.then.then.then.then.then (F:\edcertsWallet\node_modules@ngtools\webpack\src\plugin.js:495:24)
at process._tickCallback (internal/process/next_tick.js:103:7)

Angular 6

In Angular 6, got below error

ERROR in ../node_modules/ngx-cookie-service/cookie-service/cookie.service.js
Module not found: Error: Can't resolve '@angular/common' in '/node_modules/ngx-cookie-service/cookie-service'
ERROR in ../node_modules/ngx-cookie-service/cookie-service/cookie.service.js
Module not found: Error: Can't resolve '@angular/core' in '/node_modules/ngx-cookie-service/cookie-service'

Can't resolve all parameters for CookieService: (?)

Expected Behavior

I had Cookie Service integrated in my project and it worked fine. It should work now because nothing has changed.

Actual Behavior

What actually happens is that when running ionic serve I get this peculiar error "Can't resolve all parameters for CookieService: (?). It does not run. It's very annoying and weird why it even keeps the project from starting... Maybe it's not something wrong with the Cookie Service itself, but I can't get to run my project anyway.

Steps to Reproduce the Problem

...

Specifications

  • Version: Angular CLI/Core 4.1.3, Node 8.9, Ionic 3, ngx-cookie-serve 1.0.9
  • Browser: Safari
  • ...

Delete cookie is not working in IE 11

Expected Behavior

(new CookieService()).delete('somename','/','example.com') is expected to delete cookie value which already in set.

Actual Behaviour

Cookie is not getting delete.

Steps to Reproduce the Problem

  1. Write following code
(new CookieService()).delete('somename','/','yourdomain.com');
window.location.href = "http://somedoman.com"
  1. Navigate back to some page which is in yourdomain.com

NOTE: This behaviour, i have noted in outlook addin development.

Specifications

Support for Angular 5.x ?

Hey!

Angular 5 is still in beta however (it will be released in a couple of days). Can you add support to it? The peer dependencies now restrict to version 4.

How to set cookie for specific domain

I am trying to set cookie for a domain but its not working. Here is my code:
this.cookieService.set('merchant_data', cookieData, expire, '/', 'abc.example.com');

its not working but when I remove domain it works , how can I set it for domain ?

Angular 6 set cookie, get cookie in Edge not working after routing

Expected Behavior

Set cookie, try to get the cookie after routing. The cookie is not present in the browser.
It is somehow deleted. This is tested in Edge browser in Chrom everything is working.

Actual Behavior

Expect to have the cookie after routing.

Steps to Reproduce the Problem

Set cookie in the app component. Make some 'test' component, need a button on app component to route to the 'test' component, after routing, try to get the cookie.
I would make stackblitz example, but I am getting the error: pointing to non-existing "lib/index.ts" .

Specifications

/ \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|

/ △ \ | '_ \ / | | | | |/ _ | '__| | | | | | |
/ ___ | | | | (
| | || | | (| | | | || | | |
// __| ||_, |_,||_,|| _|||
|___/

Angular CLI: 6.0.0
Node: 8.11.2
OS: win32 x64
Angular: undefined
...

Package Version

@angular-devkit/architect 0.6.0 (cli-only)
@angular-devkit/core 0.6.0 (cli-only)
@angular-devkit/schematics 0.6.0 (cli-only)
@schematics/angular 0.6.0 (cli-only)
@schematics/update 0.6.0 (cli-only)
rxjs 6.1.0 (cli-only)

Browser: Edge

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.