【问题标题】:how to deal with response time for firebase auth state如何处理 Firebase 身份验证状态的响应时间
【发布时间】: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


    【解决方案1】:

    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
    

    header.component.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;
      }
    }
    

    更多信息请查看官方文档here。

    【讨论】:

    • 解析器是一种好方法,但我必须强烈反对在 ngOnInit 中调用异步不是最佳实践的说法。 ngOnInit 是理想的起点(不是构造函数),您绝对应该进行复杂的处理和初始数据获取(甚至是异步的)。在这里阅读更多:angular.io/guide/lifecycle-hooks#oninit
    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多