angular - 如何根据Angular 8中的登录状态动态隐藏sidenav项目
问题描述
我正在开发一个用于在线发票交换的小型 web-api。我决定使用 Asp.net core 作为后端,使用 Angular8 作为前端。由于我需要不会改变太多的基于角色的视图,因此我想让我的 Angular Material Sidenav 中的某些项目仅对某些用户可见。现在我正在使用*ngIf
引用包含活动用户角色的变量的语句。当我登录一个注销按钮时,应该会出现基于用户角色的列表项目,但只有在我重新加载整个页面后才会发生更改。如何更改它以便 sidenav 在某些事件上立即更新,例如登录,而无需重新加载整个页面?
我尝试使用*ngIf
与存储在相应组件和共享文件夹中的user.service.ts文件中的变量相对应的语句。我还尝试在login.component.ts中使用 EventEmitter来调用 mySidenav 中的必要更改。登录事件发生在我的登录组件中,在我的app.component.html中通过<router-outlet></router-outlet>
先感谢您 !
app.component.html
<mat-sidenav-container>
<mat-sidenav #sidenav class="sidenav" mode="push">
<mat-nav-list>
<a mat-list-item [routerLink]='["/home"]' [routerLinkActive]='["link-active"]' ><mat-icon>home</mat-icon> Home</a>
<a mat-list-item [routerLink]='["/form"]' [routerLinkActive]='["link-active"]' ><mat-icon>assignment</mat-icon> Formular</a>
<a mat-list-item [routerLink]='["/user/registration"]' [routerLinkActive]='["link-active"]' ><mat-icon>settings</mat-icon> Nutzer Verwalten</a>
<a mat-list-item [routerLink]='["/profile"]' [routerLinkActive]='["link-active"]' ><mat-icon>account_box</mat-icon> Profil</a>
<a mat-list-item [routerLink]='["/test"]' [routerLinkActive]='["link-active"]' ><mat-icon>build</mat-icon> Test Page</a>
<a *ngIf="login" mat-list-item (click)="onLogout()"><mat-icon>vpn_key</mat-icon> Logout</a>
</mat-nav-list>
</mat-sidenav>
<mat-sidenav-content class="sidenav-content">
<mat-toolbar class="toolbar mat-elevation-z12" style="background-color: lightyellow">
<button mat-icon-button (click)="sidenav.toggle()">
<mat-icon>menu</mat-icon>
</button>
SmartWeb
</mat-toolbar>
<main class="content">
<router-outlet></router-outlet>
</main>
</mat-sidenav-content>
</mat-sidenav-container>
第六个mat-list-item
对应app.component.tslogin: boolean;
中的一个变量。当用户成功提交登录表单时,登录设置为 true,但 sidenav 保持不变,直到我重新加载页面。
解决方案
如果需要,您可以使用 Subject 或 BehaviourSubject。
基本上是你的sideNav组件的onInit,订阅Subject,当用户登录或发生需要通知侧边菜单的事件时,触发Subject,
基本上,
在您可以在侧边菜单和需要触发事件的位置注入的服务中,执行
userLogin: Subject<any> //or whatever data type you are sending
constructor(){
this.userLogin = new Subject()
}
然后将服务注入到您的侧边菜单和其他组件中
当用户登录什么的时候
从源头做
x-service.userLogin.next(ANY_DATA) //or no data
在侧面菜单中
x-service.userLogin.subscribe((ANY_DATA) => {
//whatever action you want to take
})```