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:
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?
IUser,token?: string- it's optional, a given user might not have atokenproperty. But thegetDecodedTokenfunction defines its parameter astoken: string- that must be a string. Somewhere you need to deal with the fact that those don't add up - we can't tell you exactly how, you need to decide if those types are correct and, if so, what should happen ifuser.tokenisundefined.user.tokenisundefined, as the types you've defined allow it to be, when you come to pass it togetDecodedToken. Also you seem to be dealing with a token like a JWT but not actually validating it - what did you think the other parts separated by.were for?