导航栏中的角度显示帐户登录

问题描述 投票:0回答:1

我正在尝试获取用户的登录名,以将其放在导航栏component中。我首先只添加了没有eventManager的行,但是如果不刷新网页就无法看到用户名,因此我决定使用以下方法,但是我不确定如何查看广播。因此,我决定在事件管理器中使用jhipster构建。我创建了broadcast和一个subscribe

还有更好的方法吗?

this.eventManager.subscribe('userLoggedIn', () => {
  console.log('userLoggedIn called');
  this.accountService.identity().subscribe(account => {
     this.loggedinAccount = account.login;
  });
});
angular typescript jhipster
1个回答
0
投票

默认的JHipster模板实际上在主页组件(登录页面)上显示帐户登录名。我认为,只要像他们一样使用getAuthenticationState()会更容易。

navbar.component.ts中需要进行的更改才能检索身份验证状态:

export class NavbarComponent implements OnInit, OnDestroy {
  // ...
  account: Account | null = null;
  authSubscription?: Subscription;

  // constructor

  ngOnInit(): void {
    // ...
    this.authSubscription = this.accountService.getAuthenticationState().subscribe(
      account => (this.account = account)
    );
  }

  ngOnDestroy(): void {
    if (this.authSubscription) {
      this.authSubscription.unsubscribe();
    }
  }

并且在navbar.component.html中,您可以根据需要使用account.login,例如:

<span class="text-light" *ngIf="isAuthenticated()">
  Welcome {{account.login}} !
</span>
© www.soinside.com 2019 - 2024. All rights reserved.