-3

The subject exists here also, but I'm still stuck.

I have an error in the isAuth() method:

Error: src/app/services/auth.service.ts:22:38 - error TS2345: Argument of type 'string 
| null' is not assignable to parameter of type 'string | undefined'.

Type 'null' is not assignable to type 'string | undefined'.

22     if(this.jwtHelper.isTokenExpired(token) || !localStorage.getItem('token')){  

I don't understand what I have to change?

isAuth():boolean{
    const token = localStorage.getItem('token');
    if(this.jwtHelper.isTokenExpired(token) || !localStorage.getItem('token')){
      return false;
    }
    return true;
}

code

lemoine
  • 35
  • 1
  • 6

2 Answers2

0

the value of token is nullable because if there is no value for the key 'token' in your local storage, then localStorage returns null. so what you can do is: first check if there is a value for token or not.


isAuth():boolean{
    const token = localStorage.getItem('token');
    if((token && this.jwtHelper.isTokenExpired(token)) || !localStorage.getItem('token')){
      return false;
    }
    return true;
}

but the better approach is this:


isAuth():boolean{
    const token = localStorage.getItem('token');
    return token && !this.jwtHelper.isTokenExpired(token);
}

ABOS
  • 3,723
  • 3
  • 17
  • 23
qafoori
  • 781
  • 8
  • 13
0

I believe isTokenExpired() is expecting either a string or undefined, but getItem() returns a string or null.

Do something like:

return token == null ? false : this.jwtHelper.isTokenExpired(token)
Johnny
  • 1,063
  • 1
  • 11
  • 23