Can you assist me with a coding issue I'm facing? I have implemented three methods: login
, logout
, and isAuthenticated
. My goal is to securely store the token in localStorage
upon login, and display only the Logout
button when authenticated. However, after logging in and reloading the page, all three buttons are still visible instead of just the Logout
button. Even though the token is stored in localStorage
, the logic seems to be off. Could you help me identify the problem and suggest how to adjust the logic for the logout
functionality as well? Thank you in advance.
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;
}
}