我正在尝试获取用户的登录名,以将其放在导航栏component
中。我首先只添加了没有eventManager
的行,但是如果不刷新网页就无法看到用户名,因此我决定使用以下方法,但是我不确定如何查看广播。因此,我决定在事件管理器中使用jhipster
构建。我创建了broadcast
和一个subscribe
。
还有更好的方法吗?
this.eventManager.subscribe('userLoggedIn', () => {
console.log('userLoggedIn called');
this.accountService.identity().subscribe(account => {
this.loggedinAccount = account.login;
});
});
默认的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>