首页 文章

强制登录角度2上的用户名刷新

提问于
浏览
0

我在 Headers 组件中有一个导航栏,在所有路由上共享 . 我希望当前用户的用户名在他登录时显示在导航栏上 . 我已经有了这个工作但是当前用户登录后我必须在用户名出现之前手动刷新页面 .

登录系统是基于我的应用程序的令牌 . 当用户登录用户名时,令牌将保存在本地存储中 . 我可以检查登录后是否发生这种情况,但由于 Headers 不需要在登录时刷新,因此不会显示用户名 . 如果我在登录后重新加载页面,则 Headers 会正确显示用户名 .

当用户登录时,如何强制标头组件从auth服务获取用户名?

从 Headers 组件 -

export class HeaderComponent implements OnInit {
  private currentUser: User;

  constructor(
    public auth:AuthService,
    private alertService: AlertService
  ) { 
    this.currentUser = auth.getCurrentUserName();
  }
  ngOnInit() {

    }
}

认证服务..

@Injectable()
export class AuthService {
  public token: string;
  constructor(private http: HttpClient) {

public getCurrentUserId(){
     if (localStorage.getItem('currentUser')){
      return JSON.parse(localStorage.getItem('currentUser')).id;
     } else return "";
   }

2 回答

  • 2

    我建议您使用Observable:

    @Injectable()
    export class AuthService {
    private _currentUser: BehaviorSubject<string>;
    
    constructor() {
        this._currentUser = new BehaviorSubject("");
    }
    
    getCurrentUser(): Observable<string> {
        return this._currentUser.asObservable();
    }
    
    setUser(user: string) {
        this._currentUser.next(user);
    }
    

    你的组件将是这样的:

    export class HeaderComponent implements OnInit {
    private currentUser: User;
    
    constructor(
        public auth: AuthService,
        private alertService: AlertService
    ) {
        this.currentUser = auth.getCurrentUser()
            .subscribe(user => this.currentUser = user);
    }
    ngOnInit() {
    
    }
    }
    
  • 0

    我需要做的就是直接在我的模板中使用auth服务中的函数,而不是先设置局部变量 .

    <li class="nav-item dropdown ">
              <button id="navbarDropdown" role="button">
                {{auth.getCurrentUserName()}}
              </button>
              ...
    

相关问题