且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-02 14:17:40

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

In your code return this.allowed; is executed before the callback function passed to this.af.auth.subscribe(...) is executed.

应该是这样

  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()
  }