我试图在注销/注销时更改图标和按钮的功能。我写了以下代码:
navbar.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from 'src/app/services/authentication.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.scss']
})
export class NavbarComponent implements OnInit {
public loggedIn;
constructor(private authService : AuthenticationService, private router : Router) {
this.loggedIn = this.authService.isLoggedIn();
}
ngOnInit(): void {
}
logOut(){
this.authService.logout()
this.router.navigate(['/login']);
}
}
navbar.component.html
<mat-toolbar color="primary">
<mat-toolbar-row>
<span>SB Betting</span>
<span class="example-spacer"></span>
<button *ngIf="!loggedIn" mat-icon-button [routerLink]="'/login'">
<mat-icon class="example-icon" aria-hidden="false" aria-label="Login">exit_to_app</mat-icon>
</button>
<button *ngIf="loggedIn" mat-icon-button [routerLink]="'/'" (click)="logOut()">
<mat-icon class="example-icon" aria-hidden="false" aria-label="Logout">settings_power</mat-icon>
</button>
</mat-toolbar-row>
</mat-toolbar>
Upon clicking one of the buttons the icon/functionality is not changed in the navbar, the user is logged in/logged out when clicking and after refreshing the correct icon is loaded. How can I achieve this without reloading the page? I also tried putting the this.loggedIn = this.authService.isLoggedIn();
in the ngInit
method.
注销后单击时必须重新分配变量。这将更改您的按钮。