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;
}
>Solution :
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);
}