我需要你的帮助。我有很多方法:login
,logout
,isAuthenticated
。我试图确保登录时,我将令牌存储在localStorage
中,如果我有令牌,则只显示Logout
按钮。当我登录系统时,一切正常,但重新加载页面后,我看到剩下的2个按钮,而不是Logout
。虽然我在localStorage
中有令牌。告诉我我的问题是什么,以及如何为logout
配置此逻辑?非常感谢
component.ts
export class AppComponent implements OnInit {
public isAuthenticated: boolean = false;
constructor(private router: Router, private authService: AuthService) {}
ngOnInit(): void {
this.isAuthenticated = this.authService.isAuthenticated();
this.authService.isAuthenticatedSubject.subscribe(isAuthenticated=> {
this.isAuthenticated = isAuthenticated;
});
}
logout(): void {
this.authService.logout().subscribe(() => {});
}
}
component.html
<div class="buttons">
<button *ngIf="!isAuthenticated"> Login </button>
<button *ngIf="!isAuthenticated"> Signup </button>
<button (click)="logout()" *ngIf="isAuthenticated"> Logout </button>
</div>
auth.service
export class AuthService {
public isAuthenticatedSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
constructor(private httpClient: HttpClient) {}
public login(body: LoginModel): Observable<SignupLoginResponseModel> {
return this.httpClient.post<SignupLoginResponseModel>(`${environment.apiUrl}/auth/login`, body)
.pipe(
tap((response) => {
localStorage.setItem('access_token', response.access_token);
this.isAuthenticatedSubject.next(true);
})
);
}
public logout(): Observable<Object> {
return this.httpClient.post(`${environment.apiUrl}/auth/logout`, {})
.pipe(
tap(() => {
localStorage.removeItem('access_token');
this.isAuthenticatedSubject.next(false);
})
);
}
public getToken(): string {
return localStorage.getItem('access_token')!;
}
public isAuthenticated(): boolean {
const token = this.getToken();
return !!token;
}
}
1条答案
按热度按时间mkshixfv1#
如果令牌存在,则将
isAuthenticatedSubject
的值示例化为true,否则为false。