Angular 8授权指令仅在第一次使用时有效

Angular 8授权指令仅在第一次使用时有效,angular,rxjs,angular2-directives,Angular,Rxjs,Angular2 Directives,我正在根据登录用户的角色指示显示功能。 在OnInit中,我订阅了发出当前用户并将其保存在变量中的BehaviorSubject: ngOnInit(): void { this.profileService.currentProfileData$ .pipe( takeUntil(this.unsubscribe$) ) .subscribe((user: User) => { this.currentUser

我正在根据登录用户的角色指示显示功能。 在OnInit中,我订阅了发出当前用户并将其保存在变量中的BehaviorSubject:

ngOnInit(): void {
    this.profileService.currentProfileData$
      .pipe(
        takeUntil(this.unsubscribe$)
      )
      .subscribe((user: User) => {
        this.currentUser = user;
        this.updateView();
      });
  }
updateView方法负责根据用户角色显示或不显示功能:

private updateView() {
    if (!this.currentUser || !this.currentUser.roles || this.currentUser.roles.length === 0) {
      this.viewContainer.clear();
      return;
    }

    if (this.authorities.find(a => this.currentUser.roles.includes(a))) {
      if (!this.isVisible) {
        this.isVisible = true;
        this.viewContainer.createEmbeddedView(this.templateRef);
      }
    } else {
      this.isVisible = false;
      this.viewContainer.clear();
    }
  }
我得到了指令中参数的角色:

@Input()
  set hasAnyRole(value: string | string[]) {
    this.authorities = (typeof value === 'string' ? [<string>value] : <string[]>value);
  }
@Input()
set hasAnyRole(值:string | string[]){
this.authorities=(typeof value=='string'?[value]:value);
}
这是我的个人资料服务:

export class ProfileService implements OnInit {

  private currentProfileData = new BehaviorSubject<User>({} as any);
  public readonly currentProfileData$ = this.currentProfileData.asObservable();

  constructor(
    private storageService: StorageService
  ) { }

  ngOnInit(): void {
    const currentUser = this.storageService.getItem('token') ? this.storageService.getItem('user') as User : {} as any;
    this.currentProfileData = new BehaviorSubject<User>(currentUser);
  }

  changeUserInfo(user: User) {
    // Update user data in storage
    this.storageService.setItem('user', user);
    this.currentProfileData.next(user);
  }
}
导出类ProfileService实现OnInit{
private currentProfileData=新行为主体({}如有);
public readonly currentProfileData$=this.currentProfileData.asObservable();
建造师(
专用存储服务:存储服务
) { }
ngOnInit():void{
const currentUser=this.storageService.getItem('token')?this.storageService.getItem('user')作为用户:{}作为任何用户;
this.currentProfileData=新行为主体(currentUser);
}
changeUserInfo(用户:用户){
//更新存储中的用户数据
this.storageService.setItem('user',user);
this.currentProfileData.next(用户);
}
}
登录后,我在BehaviorSubject(changeUserInfo方法)中给出下一步,并发送登录的用户。 此时,指令起作用,并显示当前用户的功能。 但是,如果我移动到另一个视图,或者更新当前视图(F5),该指令将在用户中未定义并停止工作。 BehaviorSubject不应该发出最后一个值吗?在这种情况下,该值是用户登录的

有些事情我做得不好。
任何帮助都将不胜感激。

您必须使用localstorage将
currentUser
存储到localstorage中。尝试从本地存储
updateView
获取
currentUser
。如果有,就使用它或踢用户登录屏幕。是@NimittShah,就是这样。谢谢不要把它放在不安全的地方,把它放在饼干里