-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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.