如何处理firebaseauth状态的响应时间



我正在努力最大限度地减少我的web应用程序成功检查其firebase是否已通过身份验证,但我的"身份验证状态对象"似乎在我的模板上无法正常工作所需的时间(模板上的相应部分根本不会出现(

我的目标解决方案是将身份验证状态存储在本地存储中,这样,如果有人重新打开web应用程序,页面的用户身份验证部分就不会出现不稳定的负载。有人能帮助或帮助我找到一个不同/更好的解决方案吗?

我的应用程序组件在其构造函数中包含以下内容:

this.authService.authListener();

header.component.ts-我想在哪里跟踪我的用户Auth

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();
}

ngOnInit((是一个生命周期挂钩,不应用于异步调用(最佳实践(。相反,将验证代码移动到解析程序中。

auth.resolver.ts

@Injectable({ providedIn: 'root' })
export class AuthResolver implements Resolve<any> {
constructor(private authservice: AuthService) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<any>
{
return this.authService.getAuthState();
}
}

app.routing.ts

@NgModule({
imports: [
RouterModule.forRoot([
{
path: '/',
component: HeaderComponent,
resolve: {
authState: AuthResolver
}
}
])
],
exports: [RouterModule]
})

将解析器添加到提供者下的ngModule中:

providers: [AuthResolver] //Add AuthResolver to the providers array

头组件.ts

export class HeaderComponent implements OnInit {
authObj: any;
constructor(public sideNavService: SideNavService, private accountService: AccountService, private activatedRoute: ActivatedRoute) { 
}
ngOnInit(): void {
this.authState = this.route.snapshot.data['authState'].authenticated;
}
}

有关更多信息,请查看此处的官方文档。

最新更新