订阅更改时 canActivate 不响应 Angular 2 路由器 AngularFire2

canActivate doesn't respond upon subscription change Angular 2 Router AngularFire2

我正在使用 AngularFire2。这就是我使用 AuthGuard 服务的方式:

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    this.af.auth.subscribe((auth) =>  {
      if(auth == null) {
        this.router.navigate(['/login']);
        this.allowed = false;
      } else {
        this.allowed = true;
      }
    })
    return this.allowed;
  }

上面的代码有效,除了当我直接访问受保护的页面时(我在浏览器中输入 URL),它不会在订阅解析为 true 后加载相应的组件。

在 angular 1 中,保护路由是确保在路由加载之前先解决某些问题。

它出现在angular 2,路由加载(无论是true还是false,并且不等待线路的任何响应),因此到时订阅值returns为真的,我得去另一条路,然后回来才行。

保护我的路线以在 Angular 2 中响应的正确方法是什么?

在您的代码中,return this.allowed; 在执行传递给 this.af.auth.subscribe(...) 的回调函数之前执行。

应该是

  import 'rxjs/add/operator/map';
  import 'rxjs/add/operator/first';
  import { Observable } from 'rxjs/Observable';


  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.af.auth.map((auth) =>  {
      if(auth == null) {
        this.router.navigate(['/login']);
        return false;
      } else {
        return true;
      }
    }).first()
  }

如果你是来寻找 Angular 4 with angularfire 4 的,这是我调整 Gunter 答案的方式:

  canActivate(route: ActivatedRouteSnapshot):Observable<boolean>{
    return this.af.authState.map((user)=>{
      if(user != null){
        return true;
      }else{
        this._store.dispatch(new LayoutOpenLoginAction());
        return false;
      }
    }).first();
  }