I'm using BehaviorSubject to display the username in the header component after logging in, and everything works fine. However, when I reload the page, the username no longer appears. Why is this happening, and how can I fix it?
header.component.ts
export class HeaderComponent implements OnInit{
isLogin:boolean = false;
username:string = '';
searchValue = '';
form:FormGroup;
constructor(private authService:AuthenticationService,
private router:Router){
}
ngOnInit(): void {
this.isLogged();
this.getUsername();
}
isLogged(){
this.authService.currentIsLogged$.subscribe(isLoggin=> this.isLogin = isLoggin);
}
getUsername(){
this.authService.currentUsername$.subscribe(username=> this.username = username);
}
}
header.component.html个
<div class="col d-flex justify-content-end align-items-center">
<ng-container *ngIf="isLogin;else login">
<span>Hello {{username}}</span>
</ng-container>
<ng-template #login>
<button mat-icon-button [matMenuTriggerFor]="user">
<mat-icon
fontIcon="account_circle"></mat-icon>
</button>
<mat-menu #user="matMenu">
<div class="p-3 custom-size">
<a class="user-part" routerLink="/login">Login</a>
</div>
<div class="px-3 pb-3">
<a class=user-part routerLink="/register">Register</a>
</div>
</mat-menu>
</ng-template>
</div>
authentication.service.ts个
export class AuthenticationService {
isLogged = new BehaviorSubject(false);
username = new BehaviorSubject('');
currentIsLogged$ = this.isLogged.asObservable();
currentUsername$ = this.username.asObservable();
constructor(private http:HttpClient,
private tokenService:TokenService) { }
public authenticate(request:AuthenticationRequest){
return this.http.post<AuthenticationResponse>(`${AUTH_API}/auth/authenticate`, request)
.pipe(
tap(token=>{
this.tokenService.setAccessToken(token.accessToken);
this.tokenService.setRefreshToken(token.refreshToken);
this.isLogged.next(true);
this.username.next(this.tokenService.getUsername());
}),
catchError((err)=>{
console.log("Error handled by Service..." + err.status)
return throwError(()=> new Error(err.error.message));
})
);
}
}
login.component.ts
public login(authRequest:AuthenticationRequest){
let resp = this.authService.authenticate(authRequest);
resp.subscribe({
next: (data) => {
console.log(data);
this.utilService.openSnackBar('Success', 'Close')
this.router.navigate(['/home']);
},
error: (error) => {
this.utilService.openSnackBar(error, 'Close')
console.log(error);
}
});
}
Note:我的访问令牌(JWT)包含用户名和用户角色