Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"Argument of type 'string | undefined' is not assignable to parameter of type 'string'" for user.token

I am working on a project using ASP.NET Core Web API and Angular 13.

The login post request from the endpoint is:

> https://localhost:44396/api/v1/auth/login

    {
       "status_code": 200,
       "message": "Successfully Logged In",
       "result": {
           "token": "gggggffffffffffffdddddddddddd",
           "user": {
               "id": 3,
               "user_name": "smith",
               "last_login": "2022-01-03T12:35:26.0305649"
              },
           "roles": [
               "Teacher"
           ],
           "expires": "2022-01-03T14:40:33Z"
       }
    }

This is the Angular code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

user.ts:

export interface IResponse<T> {
  message: string;
  error: boolean;
  code: number;
  results: T;
}

export interface IUser {
  userName?: string;
  lastLogin?: Date;
  token?: string;
  roles?: string[];
  expires?: Date;
}

auth.service.ts:

export class AuthService {
  baseUrl = environment.apiUrl;
  private currentUserSource = new ReplaySubject<IUser>(1);
  currentUser$ = this.currentUserSource.asObservable();

  constructor(private http: HttpClient, private router: Router) { }

  login(model: any){
    return this.http.post(this.baseUrl+'auth/login', model).pipe(
      map((res: IUser)=>{
        const user = res;
        if(user){
          this.setCurrentUser(user);
        }
      })
    )
  }

  setCurrentUser(user: IUser){
    if(user){
      user.roles = [];
      const roles = this.getDecodedToken(user.token).role;//copy token to jwt.io see .role
      Array.isArray(roles) ? user.roles = roles : user.roles.push(roles);
      localStorage.setItem('user', JSON.stringify(user));
      this.currentUserSource.next(user);
    }
  }

  getDecodedToken(token: string) {
    return JSON.parse(atob(token.split('.')[1]));
  }
}

I got this error:

error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.

With this code highlighted in setCurrentUser: user.token

How do I resolve it?

>Solution :

Please try

const roles = this.getDecodedToken(user.token || '').role;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading