从 BehaviorSubject 获取用户名并在 Angular 11

问题描述

我正在创建一个 Angular 应用程序。我有 AuthenticationService 类。登录后,我将帐户对象放入 BehaviorSubject observable 中。这样我就可以订阅 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>

现在我的问题是成功登录后,标题部分中没有显示用户名。

enter image description here

但是如果我重新加载页面,则用户名会显示在标题部分。

enter image description here

我不知道为什么会发生这种情况。任何人都可以帮助我理解这个问题并获得解决方案。 我也不想将信息放在本地存储或会话中。

我也试过这种方法。而不是在构造函数中订阅可观察对象,我将代码放在 ngInit 中,如下面的代码。但它也不起作用。

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

解决方法

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

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

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