I'm using Auth0's API to handle user management. Everything is working as intended - On Login()
it properly stores local. On Logout()
it properly removes them.
However, the actual Login
button is not becoming Logout
automatically on success - It is when I hard-refresh the page, but not directly. I believe this is an issue with my binding?
Header component
authenticated: boolean; // Wasn't sure how else to filter in front-end
constructor(private authService: AuthService) { }
ngOnInit() {
this.authenticated = this.authService.isAuthenticated()
}
login() {
this.authService.login();
}
logout() {
this.authService.logout();
}
}
HTML For Header
<li class="nav-item">
<a class="nav-link waves-light" *ngIf="!authenticated" mdbRippleRadius (click)="login()"><i class="fa fa-user"></i> <span class="clearfix d-none d-sm-inline-block">Log In</span></a>
<a class="nav-link waves-light" *ngIf="authenticated" mdbRippleRadius (click)="logout()"><i class="fa fa-user"></i> <span class="clearfix d-none d-sm-inline-block">Log Out</span></a>
</li>
The docs said to use auth.isAuthenticated()
which would call the function from the service
public isAuthenticated(): boolean {
// Check whether the current time is past the
// access token's expiry time
const expiresAt = JSON.parse(localStorage.getItem('expires_at'));
return new Date().getTime() < expiresAt;
}
I was thinking perhaps I should append this.authenticated = this.authService.isAuthenticated()
to the end of each login()/logout()
function in the header component, but I'm feeling like I'm going the wrong direction with this.
Welcome any input.
Update
Modifying logout()
to call this.authenticated = this.authService.isAuthenticated()
did resolve the issue for it, but Login is still not becoming Log Out until I refresh the page.
You can write authenticated
as a property getter:
public get authenticated(): boolean {
return this.authService.isAuthenticated();
}
From what I can see you're only updating your variable on init. That's why you only see the changes when you refresh. If you do
login() {
this.authService.login();
this.authenticated = this.authService.isAuthenticated()
}
Inside the login method it should work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.