I am using angular 7 and I have implement within the Auth service Login method a call to a method os the same service to set a variable of such method:
export class AuthService {
private url:string = 'http://localhost:8080/Auth';
private token:string;
private expiresAt: number;
private CurrentUsername : string = null;
private currentUserId : number = null;
public CurrentUserroles : RoleModelDTO[];
constructor(private http: HttpClient, private router: Router, private userService: UserService) { }
login(loginModel : LoginModelDTO){
const headers = new HttpHeaders(
{
'Content-Type': 'application/json'
}
);
this.http.post(`${this.url}/login`,loginModel,{headers}).subscribe(
(resp: LogedUserModelDTO) => {
console.log(resp);
this.setToken(resp.token);
this.setExpiresAt(resp.expire);
this.setCurrentUserName(resp.username);
this.setCurrentUserId(resp.userId);
this.setCurrentUserroles(resp.roles);
this.router.navigate(['/MyAPP/profile', resp.userId]);
},
(error: HttpErrorResponse) => {
console.log(error);
Swal.close();
this.handelError(error,'login Error');
}
);
logout(){
this.token = null;
this.expiresAt = null;
this.setCurrentUserroles = null;
this.setCurrentUserName = null;
this.setCurrentUserId = null;
localStorage.clear();
this.router.navigateByUrl('/login');
}
}
getRoles(){
let token : string = this.getToken();
const headers = new HttpHeaders(
{
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
);
return this.http.get(`${this.url}/getRoles`,{headers} )
}
private setToken(token : string){
this.token = token;
}
getToken() : string{
return this.token;
}
private setExpiresAt(expire:number){
this.expiresAt = (expire * 1000) + Date.now();
}
setCurrentUserName(username : string){
this.CurrentUsername = username;
}
getCurrentUserName() : string{
return this.CurrentUsername
}
setCurrentUserId(userId : number){
this.currentUserId = userId;
}
getCurrentUserId() : number{
return this.currentUserId;
}
setCurrentUserroles(CurrentUserroles : RoleModelDTO[]){
this.CurrentUserroles = CurrentUserroles;
}
getCurrentUserroles() : RoleModelDTO[] {
return this.CurrentUserroles;
}
}
(I have not included all code of the service because its so big)
As you can see, when login, there is a method: this.setCurrentUserName(resp.username);
the first time I try to log in everuthing works fine:
But then if I logout anfd try to login again i get this error:

When I press F5 and reload the page it works fine again.
I dont understand why reloading the page it works and what I a doing wrong when it is just a simple method in the same service.
Thank you!
IMPORTANT
I Know i can just do this: this.CurrentUsername = resp.username; this.currentUserId = resp.userId;
and so on, but i dont want to do this because this methods were first in another service with the same error and I want to know what produces it