使用ChangeDetectorRef

问题描述

我遇到了一个小问题,在这些日子之一中,我似乎找不到合适的解决方案。我尝试了类似问题的一些解决方案,但没有成功。

用户注销后,所有链接均被禁用。用户登录后,只有当用户没有角色Admin时,才应禁用某些链接

我已经阅读了大多数类似的问题,并提出了EventEmitterService来从app.component.ts调用login.component.ts中的方法app.component.ts中的被调用方法调用this.changeDetectorRef.detectChanges()

但是,尽管登录用户具有Admin的角色,但链接仍然被禁用。

app.component.ts

export class AppComponent implements OnInit {
  navLinks = [
    { path: 'hello',label: 'Hello' },{ path: 'administration',label: 'Administration',role: 'admin' }
  ];

  private roles: string[];
  isAdmin = false;

  constructor(
    ...
    private eventEmitterService: EventEmitterService,private cdr: ChangeDetectorRef) {
    
  }

  ngOnInit() {
    if (this.eventEmitterService.subsVar === undefined) {
      this.eventEmitterService.subsVar = this.eventEmitterService.
      invokeRoleRefreshFunction.subscribe((name: string) => {
        this.updateRoles();
      });
    }
    ...
  }

  updateRoles() {
    const user = this.tokenStorageService.getUser();

    this.roles = user.roles;
    console.log(this.roles);

    this.isAdmin = this.roles.includes('ROLE_ADMIN');

    this.cdr.detectChanges();
    }
  }

app.component.html

<nav mat-tab-nav-bar>
  <a mat-tab-link
     *ngFor="let link of navLinks"
     [disabled]="link.role === 'admin' && !isAdmin || !isLoggedIn"
     [routerLink]="link.path"
     routerLinkActive #rla="routerLinkActive"
     [routerLinkActiveOptions]="{exact:true}"
     [active]="rla.isActive">
    {{link.label}}
  </a>
</nav>

login.component.ts

export class LoginComponent implements OnInit {

  constructor(private eventEmitterService: EventEmitterService) { }

  onLogin() {
    ...
    this.eventEmitterService.onLogin();
  }
}

很抱歉缺少StackBlitz。希望有人能给我提示

非常感谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)