首页 > 解决方案 > 在组件angular7中显示当前用户的用户名

问题描述

我在身份验证服务中创建了一个发出用户全部数据的主题。在标题组件中,我订阅了那个 observable。一切都应该正常,但它没有显示任何数据。这是 auth 服务中的 autoAuth 功能。

autoAuthUser() {
      const authInformation = this.getAuthData();
      if (!authInformation) {
        return;
      }
        this.authStatusListener.next(true);
        this.fetchUser(authInformation.userId).subscribe(
          (res) => {
            if (res.user) {
              this.currentUser = res.user;
              this.userListener.next(this.currentUser);
            }
          }
        );
      }
    }

这是在标题组件中:

this.authService.autoAuthUser();
        this.authService.getAuthStatusListener().subscribe((isA) => {
            this.isAuthenticated = isA;
            if (this.isAuthenticated) {
            this.authService.getUserListener().subscribe(
            (user) => {
                this.currentUser = user;
            }
        );
      }

这是在标题组件的模板中:

<p class="username">{{currentUser?.username}}</p>

当我在标题组件中控制台记录当前用户时,我得到了整个正确的数据,但它没有显示任何内容。

标签: angular

解决方案


在标题组件中,将this.authService.autoAuthUser();调用移动到底部。

这应该工作

this.authService.getUserListener().subscribe((user) => {
    this.currentUser = user;
});

this.authService.getAuthStatusListener().subscribe((isA) => {
    this.isAuthenticated = isA;
});

this.authService.autoAuthUser();

推荐阅读