【发布时间】:2020-03-27 19:03:37
【问题描述】:
我正在尝试最大程度地减少我的 Web 应用程序成功检查其 Firebase 是否已通过身份验证所需的时间,但我的“身份验证状态对象”似乎在我的模板上无法正常工作(模板上的相应部分没有完全出现)
我的目标解决方案是将身份验证状态存储在本地存储中,这样如果有人重新打开 Web 应用程序,页面的用户身份验证部分就不会出现断断续续的负载。任何人都可以帮助或帮助我寻求不同/更好的解决方案吗?
我的应用组件在其构造函数中包含以下内容:
this.authService.authListener();
header.component.ts - 我想在其中跟踪我的用户身份验证
export class HeaderComponent implements OnInit {
authObj: Observable<any>;
constructor(public sideNavService: SideNavService, private accountService: AccountService, private authService: AuthenticationService) {
}
ngOnInit(): void {
this.authObj = this.authService.getAuthState();
}
}
header.component.html
<div *ngIf="authObj | async as authObj">
<div *ngIf="!authObj.authenticated" class="header-ctas" fxHide.lt-md>
<button mat-button [routerLink]="['/account/create']" class="btn-register">Register</button>
<button mat-button [routerLink]="['/account/login']" class="btn-login">Account Login</button>
<mat-icon routerLink="['/']">shopping_cart</mat-icon>
</div>
<div *ngIf="authObj.authenticated" class="header-ctas" fxHide.lt-md>
<button mat-button (click)="accountService?.logout()" class="btn-register">Logout</button>
<mat-icon routerLink="['/']">shopping_cart</mat-icon>
</div>
</div>
我的身份验证服务具有以下内容:
public authListener() {
let userAuthObj = JSON.parse(localStorage.getItem('userAuth'));
if (userAuthObj && userAuthObj.authenticated) {
this.authenticationState.next(userAuthObj);
} else {
this.fireAuth.authState.subscribe(user => {
localStorage.setItem('userAuth', JSON.stringify({ user: user ? user : null, authenticated: user ? true : false }));
this.authenticationState.next(JSON.parse(localStorage.getItem('userAuth')));
});
}
}
public getAuthState() {
return this.authenticationState.asObservable();
}
【问题讨论】:
标签: angular typescript firebase firebase-authentication