【问题标题】:Angular LoggedIn methodAngular LoggedIn 方法
【发布时间】:2021-04-06 17:23:01
【问题描述】:

如何在AuthService 中添加loginIn 方法,以便获得有关用户状态的布尔值?我想要它用于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);
}

【问题讨论】:

    标签: angular typescript firebase


    【解决方案1】:

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

    【讨论】:

    • 和注销:`logout(){ this.isAuthenticatd = false; this.user.next(); this.router.navigate(['/auth0']); } 登录方法: isLoggedIn(){ if (this.isAuthenticad === true ) { return true;} else {return false} } }`
    • 有时,当登录仍未完成时,就像角度尝试路由一样,一旦用户在服务中正确设置,您需要确保调用导航,然后您尝试签入保护当您通过该服务调用服务时会收到值
    • 您的代码也可以激活,组件中是否订阅了 http 调用?
    猜你喜欢
    • 2020-11-15
    • 2011-12-30
    • 2020-10-03
    • 2023-03-13
    • 2020-11-22
    • 1970-01-01
    • 2020-01-23
    • 2017-09-13
    • 1970-01-01
    相关资源
    最近更新 更多