Bonjour à tous,

je suis en train de mettre en place JWT Token sur un projet angular et je retrouve avec les erreurs suivante:

Error: src/app/shared/services/auth.service.ts:103:7 - error TS2322: Type 'null' is not assignable to type 'Token'.

src/app/shared/interfaces/jwt-token.interface.ts:6:3

The expected type comes from property 'token' which is declared here on type 'JwtToken'

j'ai donc deux interfaces

import { Token } from "./token.interface";
import { User } from "./user.interface";

export interface JwtToken {
  isAuthenticated: boolean;
  token: Token;
  user?: User;
}
export interface Token {
    token: string;
    refresh_token: string;
}

et mon service auth

import { Injectable } from "@angular/core";
import { User } from '../interfaces/user.interface';
import { Observable, BehaviorSubject, timer, of, Subscription } from "rxjs";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { JwtToken } from "../interfaces/jwt-token.interface";
import { tap, switchMap } from "rxjs/operators";
import { Router } from "@angular/router";

@Injectable()
export class AuthService {
  public subscription: Subscription;

  public jwtToken: BehaviorSubject<JwtToken> = new BehaviorSubject<JwtToken>({
    isAuthenticated: false,
    token: null,
  });

  constructor(private http: HttpClient, private router: Router) {
    this.initToken();
    this.subscription = this.initTimer();

  }

  public initTimer() {
    return timer(2000, 5000)
      .pipe(
        switchMap(() => {
          if (localStorage.getItem("jwt")) {
            return this.http.get<string>("/api/token/refresh").pipe(
              tap((token: string) => {
                this.jwtToken.next({
                  isAuthenticated: true,
                  token: token,
                });
                localStorage.setItem("jwt", token);
              })
            );
          } else {
            console.log("no token to refresh");
            this.subscription.unsubscribe();
            return of(null);
          }
        })
      )
      .subscribe(
        () => {},
        (err) => {
          this.jwtToken.next({
            isAuthenticated: false,
            token: null,
          });
          localStorage.removeItem("jwt");
          this.subscription.unsubscribe();
        }
      );
  }

  private initToken(): void {
    const token = localStorage.getItem("jwt");
    if (token) {
      this.jwtToken.next({
        isAuthenticated: true,
        token: token,
      });
    } else {
      this.jwtToken.next({
        isAuthenticated: false,
        token: null,
      });
    }
  }

  public inscription(user: User): Observable<User> {
    return this.http.post<User>("/api/users", user);
  }

  public connexion(credentials: {
    email: string;
    password: string;
  }): Observable<string> {
    return this.http.post<string>("/api/login", credentials).pipe(
      tap((token: string) => {
        this.jwtToken.next({
          isAuthenticated: true,
          token: token,
        });
        localStorage.setItem("jwt", token);
        //this.subscription = this.initTimer();
        //const obj = JSON.parse(this.jwtToken.value.token);
        //const valeur = this.jwtToken.value.token;
        //const obj = JSON.parse(valeur!);

        console.log(this.jwtToken.value);
      })
    );
  }

  public logout(): void {
    this.jwtToken.next({
      isAuthenticated: false,
      token: null,
    });
    localStorage.removeItem("jwt");
    this.router.navigate(["/signin"]);
  }

}

1 réponse


Pas tres sur de moi, mais j'ai l'impression que c'est typescript qui rale.

Ton interface JwtToken prends un Token pour la propriétée token, selon comment typescript est configuré, il peut refuser d'affecter la valeur null à cette propriétée. Tu peux éssayer :

export interface JwtToken {
  isAuthenticated: boolean;
  token: Token|null;
  user?: User;
}

pour autoriser null à cette endroit.