首页 > 解决方案 > 从 BehaviorSubject 获取用户名并在 Angular 11 中登录后在标题部分显示用户名需要刷新

问题描述

我正在创建一个角度应用程序。我有 AuthenticationService 类。登录后,我将帐户对象放入 BehaviorSubject 可观察对象中。这样我就可以订阅 observable 并获取 Account 对象的必要信息。这是我的代码:

private accountSubject: BehaviorSubject<AccountInfo>;
    public account: Observable<AccountInfo>;

    constructor(
        private router: Router,
        private service: ApplicationService) {

        // behaviour subject
        this.accountSubject = new BehaviorSubject<AccountInfo>(JSON.parse(localStorage.getItem('account')));
        this.account = this.accountSubject.asObservable();
    }

    public get accountValue(): AccountInfo {
        return this.accountSubject.value;
    }

    login(username: string, password: string) {
        return this.service.post<any>(`${this.apiPATH}login`, { username, password })
            .pipe(map(user => {             
                localStorage.setItem('account', JSON.stringify(user.account));
                this.accountSubject.next(user);
                return user;
            }));
    }

现在登录后我想在我的标题部分显示用户名。因此,在标头组件中,我订阅了观察者并尝试通过字符串插值显示用户名。这是我的标题组件代码:

account: AccountInfo;
    username: string;
    userPhotoUrl: string;

    constructor(private authService: AuthenticationService) {
        this.authService.account.subscribe(x => this.account = x);      
    }

    logout() {
        this.authService.logout();
    }

    ngOnInit() {        
        this.username = this.account.name;
    }

看法

<h5 class="mb-0 text-white nav-user-name">{{username}}</h5>

现在我的问题是成功登录后用户名没有显示在标题部分。 在此处输入图像描述

但是,如果我重新加载页面,则用户名将显示在标题部分。 在此处输入图像描述

为什么会发生这种情况我不知道。谁能帮我理解这个问题并得到解决方案。我也不想将信息放在本地存储或会话中。

我也尝试过这种方式。相反,在构造函数中订阅 observable,我将代码放在 ngInit 中,如下面的代码。但它也不起作用。

ngOnInit() {
    this.authService.account.subscribe(x => {
       this.account = x;
       this.username = x.name;
      }); 
}

标签: angularangular2-observables

解决方案


这可能只是一个时间问题,可能ngOnInit是在设置之前被调用account,或者没有触发更改检测。尝试对构造函数中的订阅进行以下更新

constructor(private cd: ChangeDetectorRef) {
 this.authService.account.subscribe(x => {
   this.account = x
   this.userName = this.account.name;
   // log the result to be sure it's actually being received
   console.log('account: ', x)
   // in case it's not detecting changes
   this.cd.detectChanges()
 })
}

推荐阅读