0

i have a Authentication Service in Angular, which should handle log in and out for me. So this is an @Injectable({providedIn: 'root'}).

In this service i want to use the ngx-cookie-service (https://www.npmjs.com/package/ngx-cookie-service).

My system is running on angular 14.

When i try to run it, i get the error ERROR Error: NG0203: inject() must be called from an injection context (a constructor, a factory function or a field initializer). Find more at https://angular.io/errors/NG0203

My AuthenticationService:

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {

  readonly url: string = 'http://localhost:4200/api/';
  statusSubject: ReplaySubject<boolean> = new ReplaySubject<boolean>(1);
  userType: UserTypes = UserTypes.User;
  cookieService: CookieService | undefined;


  constructor(
    private httpClient: HttpClient,
    private backendService: BackendService,
    private addressStore: AddressStore,
    private orderStore: OrderStore,
    private shoppingCartStore: ShoppingCartStore,
    private userStore: UserStore,
    private wishlistStore: WishlistStore
  ) {
    this.cookieService = inject(CookieService);
    if (this.cookieService.get("sessionKey") != null) {
      this.statusSubject.next(true);
    } else {
      this.statusSubject.next(false);
    }

  }

  login(){...}
  logout(){...}
}

How can I use the CookieService in mine?

Thanks for your help!

2 Answers2

0

To use the cookies service you musk inject it in the constructor function. It then becomes available in your component. I commented the lines in your snippet that you don't need:

    @Injectable({
      providedIn: 'root'
    })
    export class AuthenticationService {

      readonly url: string = 'http://localhost:4200/api/';
      statusSubject: ReplaySubject<boolean> = new ReplaySubject<boolean>(1);
      userType: UserTypes = UserTypes.User;
      // cookieService: CookieService | undefined;


      constructor(
        private httpClient: HttpClient,
        private backendService: BackendService,
        private addressStore: AddressStore,
        private orderStore: OrderStore,
        private shoppingCartStore: ShoppingCartStore,
        private userStore: UserStore,
        private wishlistStore: WishlistStore,
        // You must add this line:
        private cookieService: CookieService
      ) {
        // this.cookieService = inject(CookieService);
        if (this.cookieService.get("sessionKey") != null) {
          this.statusSubject.next(true);
        } else {
          this.statusSubject.next(false);
        }

      }

      login(){...}
      logout(){...}
    }
JuanDeLasNieves
  • 354
  • 1
  • 3
  • 8
  • Thanks for your Suggestion, I've tried before, but then i get the following error: `Error: NG0203: inject() must be called from an injection context (a constructor, a factory function or a field initializer). Find more at https://angular.io/errors/NG0203` – Jakob Priesner Jul 03 '22 at 12:28
  • Make sure you delete (or comment) the lines that I commented in your code. You don't need to use `inject` function at all, just adding the service in the constructor takes care of all that. – JuanDeLasNieves Jul 03 '22 at 13:03
  • The "Usage" section in the [npm package page](https://www.npmjs.com/package/ngx-cookie-service#usage) is pretty self explanatory. Also, check if you added `CookieService` correctly to the `providers` array in your `app.module.ts`. – JuanDeLasNieves Jul 03 '22 at 13:10
  • still without the lines, i am getting this error (BG0203). To add the CookieService to the providers doesnt help. – Jakob Priesner Jul 03 '22 at 20:41
0

I have the same problem that you have, and most of the examples you can find online are using ngx-cookie-service in the component, and not in a service.

I was able to solve this by extending my auth service to use ngx-cookie-service like this.

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

// 3rd party library
import {CookieService} from 'ngx-cookie-service';


const TOKEN_KEY = 'auth-token';


@Injectable({
    providedIn: 'root'
})

export class TokenStorageService extends CookieService {
    constructor(@Inject(DOCUMENT) private _document: any,
                @Inject(PLATFORM_ID) private _platformId: any) { 
        super(_document, _platformId);
    }

    public deleteToken(): void{
        this.delete(TOKEN_KEY);
    }

    public saveToken(token: string): void{
        this.delete(TOKEN_KEY);
        this.set(TOKEN_KEY, token);
    }

    public getToken(): any {
        return this.get(TOKEN_KEY);
    }

}

This way, you won't be dealing with the injection error NG0203