使用CanActivate的AngularFire2身份验证无效

时间:2016-09-09 22:51:08

标签: angular angular2-routing angularfire2

使用AngularFire2的Angular 2 RC6。我的身份验证工作导致重定向到受保护的路由(" / feed")。当authGuard中的canActivate方法触发时,身份验证始终为空。似乎在构造防护之前就进行了身份验证,因此守卫中的订阅什么都不做。

login.ts(此身份验证有效并重定向到' feed')

constructor(public af: AngularFire, private router: Router) {
  this.af.auth.subscribe(auth => console.log(auth));
}
login() {
  this.af.auth.login({
    provider: AuthProviders.Facebook,
    method: AuthMethods.Popup,
  }).then((x: FirebaseAuthState) => {
    console.log(x);
    this.router.navigate(['/feed']);
  }).catch(x => console.log(x));
}

feed.routes.ts

export const feedRoutes: Routes = [
  {
    path: '',
    component: FeedComponent,
    canActivate: [AuthGuard]
  }
];

AUTH-guard.service.ts

import { Injectable }             from '@angular/core';
import { CanActivate, Router,
        ActivatedRouteSnapshot,
        RouterStateSnapshot }    from '@angular/router';
import { AngularFire, AngularFireAuth, FirebaseAuthState }            from 'angularfire2';
import { Observable } from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivate {
  auth: FirebaseAuthState;

  constructor(private af: AngularFire, private router: Router) {
    console.log('auth guard constructed');
    this.af.auth.subscribe(authState => console.log(authState));
    this.af.auth.subscribe(x => this.auth = x);
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    console.log('can activate ' + this.auth)
    if (this.auth == null){
      // this part always fires
      console.log('no auth!')
      this.router.navigate(['/login']);
      return false;
    } 
      console.log('authenticated');
    return true;
  }
}

以下是打印到控制台的内容:

Object {auth: W, uid: "xYFs8kMDpKdYKxDw4AL21FtnSWn1", provider: 2, facebook: Of}
auth-guard.service.ts:13 auth guard constructed
auth-guard.service.ts:19 can activate undefined
auth-guard.service.ts:21 no auth!

请注意.subscribe中的操作永远不会发生。

1 个答案:

答案 0 :(得分:1)

你可能想要这样的东西:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    console.log("canActivate");
    return this.af.auth.take(1).map(auth => {
      console.log("auth:" + auth);
      if (!auth) {
        this.router.navigateByUrl('/login');
        return true;
      }
      return !!auth;
    });
  }

但是auth observable也没有为我开火。