AuthGuard 在检查用户之前不等待身份验证完成 [英] AuthGuard doesn't wait for authentication to finish before checking user

查看:21
本文介绍了AuthGuard 在检查用户之前不等待身份验证完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里阅读了指南:https://angular.io/docs/ts/latest/guide/router.html

看起来很简单,但是,我不确定如何在身份验证保护 (canActivate) 中使用 angularfire2 的身份验证.我试过的是:

Seems pretty straightforward, however, I'm not sure how to use angularfire2's authentication within an auth guard (canActivate). What I've tried is:

AuthService

import { Injectable } from '@angular/core';
import { AngularFire } from 'angularfire2';

@Injectable()
export class AuthService {

  private user: any;

  constructor(private af: AngularFire) {
    this.af.auth.subscribe(user => {
      this.user = user;
    })
  }

  get authenticated(): boolean {
    return this.user ? true : false;
  }

}

AuthGuard

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private router: Router, private authService: AuthService) { }

  canActivate(): Observable<boolean> | boolean {
    if (this.authService.authenticated)
      return true;

    this.router.navigate(['/login']);
    return false;
  } 

}

我还向引导程序提供程序添加了 AuthService.

I've also added AuthService to bootstrap providers.

这种工作正常,但是,我的主要问题是当我刷新(或最初加载)具有 AuthGuard 的页面时,它总是将我重定向到登录页面,因为 AuthGuard 不等待身份验证响应.有没有办法等待认证完成(即使失败)然后然后检查用户是否通过了认证?

This sort of works fine, however, my main problem is when I refresh (or initially load) the page on that has AuthGuard it always redirects me to the login page since the AuthGuard doesn't wait for the authentication response. Is there a way to wait for the authentication to finish (even if it's failed) and then check whether the user is authenticated?

推荐答案

问题在于您的代码.在 AuthGuard 中,您检查 authenticated() 方法的结果,该方法很可能会返回 false,因为用户属性仍未设置.试试这个:

The problem is with your code. In the AuthGuard you check the result of authenticated() method that will most probably return false as the user property is still not set. Try this:

AuthService:

import { Injectable } from '@angular/core';
import { AngularFire } from 'angularfire2';';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthService {

  private user: any;

  constructor(private af: AngularFire) { }
  setUser(user) { this.user = user; }
  getAuthenticated(): Observable<any> { return this.af.auth; }
}

AuthGuard:

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private router: Router, private authService: AuthService) { }

  canActivate(): Observable<boolean> | boolean {
    // here check if this is first time call. If not return 
    // simple boolean based on user object from authService
    // otherwise:

    return this.authService.getAuthenticated.map(user => {
          this.authService.setUser(user);
          return user ? true : false;
    })

  } 
}

这篇关于AuthGuard 在检查用户之前不等待身份验证完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆