首页 > 解决方案 > Angular LoggedIn 方法

问题描述

如何添加loginIn 方法AuthService以便获得关于用户状态的布尔值?我想要它的CanActivate方法和AuthService看起来像这样:

login(email: string, password: string) {
      return this.http.post<AuthResponseData>(
        'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=',
      {
         email,
         password,
         returnSecureToken: true
      }
      )
        .pipe(tap(resData => {
          this.handleAuthentication(
            resData.email,
            resData.localId,
            resData.idToken,
            +resData.expiresIn);
          })
        );
        }

  // tslint:disable-next-line:typedef
    private handleAuthentication(
      email: string,
      userId: string,
      token: string,
      expiresIn: number) {
        const expirationDate = new Date(new Date().getTime() + expiresIn * 1000);
        const user = new User(
          email,
          userId,
          token,
          expirationDate
           );
        this.user.next(user);
}

标签: angulartypescriptfirebase

解决方案


登录成功后,您可以将 auth 服务中的变量设置为 true 并在注销时设置为 false 然后在服务中创建一个方法作为 getauthstatus,一旦您在 canActivate 构造函数中注入 authservice 类,您就可以访问该方法或更精确的是不要创建额外的变量,只需检查您在 getloggedin 状态下创建的用户对象的可用性,并且可以将其注入到 canActivate 构造函数中


推荐阅读