Angular 如何检查是否满足条件并显示导航栏

Angular how to chekc if condition is met and show navbar

提问人:weinde 提问时间:11/14/2023 更新时间:11/15/2023 访问量:54

问:

在我的第二个 angular 项目中,我有一个导航栏,我想让它仅在用户登录后可见,并在他登录或未登录时使其不可见。在这个导航栏中,还有用户的名称......

因此,到目前为止,我设法实现的是,在登录时,用户名会显示在导航栏中,但只有在我刷新页面之后才会显示。注销后,即使我清理了本地存储,名称也会保留在导航栏中......

我不知道该怎么做并且遇到麻烦的是,我无法使导航栏不显示在登录页面上,并且在用户登录后,其他子页面上才会显示导航栏。并且再次注销以隐藏导航栏......

我希望我清楚我的问题是什么以及我遇到了什么问题......

这是我的代码(我只粘贴了与登录名和导航栏相关的代码):

HTML comonent tempalte:

  <mat-sidenav-content>
    <mat-toolbar *ngIf="currentUser" class="crm-main-toolbar">
      <button mat-icon-button (click)="sidenav.toggle()" class="menu-togle">
        <mat-icon class="material-symbols-outlined" *ngIf="sidenav.opened">chevron_left</mat-icon>
        <mat-icon class="material-symbols-outlined" *ngIf="!sidenav.opened">menu</mat-icon>
      </button>
      <img src="/assets/icons/logo-white.svg" alt="" class="logo" fxShow.xs="false" routerLink="/dashboard"/>
      <img src="/assets/icons/logotype.svg" alt="" class="logo-mobile" fxHide.xs="false" fxHide.gt-xs="true" routerLink="/dashboard"/>
      <span class="toolbar-spacer"></span>
      <p *ngIf="currentUser" class="user-name" fxShow.xs="false">{{ currentUser.user_name}}</p>
      <button mat-icon-button [matMenuTriggerFor]="userMenu" class="circle-button white user-menu">
        <i class="zwicon-user"></i>
      </button>
      <mat-menu #userMenu="matMenu">
        <button mat-menu-item routerLink="/login">
          <mat-icon class="material-symbols-outlined">account_circle</mat-icon>
          My profile
        </button>
        <button mat-menu-item (click)="logout()">
          <mat-icon class="material-symbols-outlined">logout</mat-icon>
          Logout
        </button>
      </mat-menu>
    </mat-toolbar>
    <div id="content" [ngClass]="{'content-padding' : currentUser}">
      <router-outlet></router-outlet>
    </div>

  </mat-sidenav-content>

下面是 component.ts 代码:

export class MainNavComponent implements OnInit, OnChanges{
  currentUser: User;
  currentUserSubscription: Subscription;

  constructor(
    private authService: AuthenticationService,
    private router: Router,
  ) {
    this.currentUserSubscription = this.authService.login().subscribe(user => {
      this.currentUser = user;
    })

  }
  ngOnInit() {
    this.currentUser = this.authService.getUser();
  }

  ngOnChanges() {
    this.currentUser = this.authService.getUser();
  }

  async logout() {
    this.authService.logout();
    await this.router.navigate(['/login']);
  }

}

以下是身份验证服务代码:

export class AuthenticationService {
  token = '';
  user: User;

  login(): Observable<User> {
    const params = new HttpParams().append('param', 'value');
    return this.http.get<User>(`${environment.apiUrl}azure` + location.search, {params}).pipe(
      tap((response: any) => {
        console.log('Response from login:', response);
        if (response && response.token) {
          localStorage.setItem('TOKEN_KEY', response.token);
          localStorage.setItem('username',response.user_name);
          localStorage.setItem('useremail',response.user_email);
          this.setAuthToken(response.token);
          this.isLoggedIn = true;
        } else {
          this.router.navigate(['/login']);
          return;
        }
      }),
      catchError(error => {
        console.error('Error:', error);
        return throwError(error);
      })
    );
  }

  isLogedIn() {
    const token = localStorage.getItem('TOKEN_KEY');
    return !!token;
  }

  getUser() {
    const username = localStorage.getItem('username');
    const useremail = localStorage.getItem('useremail');
    const token = localStorage.getItem('TOKEN_KEY');

    let userModel = new UserModel();
    userModel.user_email = useremail;
    userModel.user_name = username;
    userModel.token = token;
    
    console.log(userModel);
    
    return userModel;
  }

  setAuthToken(token: string) {
    this.authToken = token;
  }

  getAuthToken(): string | null {
    return this.authToken;
  }

  logout() {
    this.isLoggedIn = false;
    localStorage.removeItem("TOKEN_KEY");
    localStorage.removeItem("username");
    localStorage.removeItem("useremail");
  }
}

这是我的用户model.ts文件代码:

export interface User {
  token: string;
  user_email: string;
  user_name: string;
  validity: number;
}

export class UserModel {
  token:string;
  user_email: string;
  user_name: string;
  validity: number;
}
javascript html 打字稿 angular material

评论


答:

0赞 Mesa 11/14/2023 #1

您可以使用 Angular 的 ngIf 指令,它支持有条件的结构更改,例如在 HTML 中检查布尔值isLoggedIn = true

这是您的 HTML 代码:

<mat-toolbar *ngIf="currentUser" class="crm-main-toolbar">
  <button mat-icon-button (click)="sidenav.toggle()" class="menu-togle">
    <mat-icon class="material-symbols-outlined" *ngIf="sidenav.opened">chevron_left</mat-icon>
    <mat-icon class="material-symbols-outlined" *ngIf="!sidenav.opened">menu</mat-icon>
  </button>
<!--Here I added the ngIf conditional statement to test-->
<p *ngIf="true">
  This should be visible for *ngIf="true", set true to false to hide
</p>
<!--Here testcode ends-->
  <img src="/assets/icons/logo-white.svg" alt="" class="logo" fxShow.xs="false" routerLink="/dashboard"/>
  <img src="/assets/icons/logotype.svg" alt="" class="logo-mobile" fxHide.xs="false" fxHide.gt-xs="true" routerLink="/dashboard"/>
  <span class="toolbar-spacer"></span>
  <p *ngIf="currentUser" class="user-name" fxShow.xs="false">{{ currentUser.user_name}}</p>
  <button mat-icon-button [matMenuTriggerFor]="userMenu" class="circle-button white user-menu">
    <i class="zwicon-user"></i>
  </button>
  <mat-menu #userMenu="matMenu">
    <button mat-menu-item routerLink="/login">
      <mat-icon class="material-symbols-outlined">account_circle</mat-icon>
      My profile
    </button>
    <button mat-menu-item (click)="logout()">
      <mat-icon class="material-symbols-outlined">logout</mat-icon>
      Logout
    </button>
  </mat-menu>
</mat-toolbar>
<div id="content" [ngClass]="{'content-padding' : currentUser}">
  <router-outlet></router-outlet>
</div>

评论

0赞 weinde 11/15/2023
在 HTML 模板中?
0赞 Mesa 11/15/2023
是的,在我提供的文档链接中,有多个示例,说明从简单到复杂的几种变体,这是速记形式<div *ngIf="condition; then thenBlock else elseBlock"></div> <ng-template #thenBlock>Content to render when condition is true.</ng-template> <ng-template #elseBlock>Content to render when condition is false.</ng-template>
0赞 Community 11/15/2023
正如目前所写的那样,你的答案尚不清楚。请编辑以添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。您可以在帮助中心找到有关如何写出好答案的更多信息。