I'm currently engaged in a project that involves ASP.NET Core Web API and Angular 13.
Here is the login post request from the endpoint:
> 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"
}
}
Below is the Angular code snippet:
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]));
}
}
An error was encountered with the following message:
error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
The problematic code line highlighted is within setCurrentUser
: user.token
How can I resolve this issue?