2016-09-09 50 views
1

使用AngularFire2的Angular 2 RC6。我的身份驗證工作會導致重定向到保護的路由(「/ feed」)。當AuthGuard中的canActivate方法觸發時,身份驗證始終爲空。看起來好像認證在守衛被建造之前就發生了,所以守衛中的訂閱什麼都不做。使用CanActivate的AngularFire2身份驗證不起作用

login.ts(該認證作品和重定向到 '進料')

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中的操作不會發生。

+0

我會仔細看看你在登錄和警衛中使用的'console.log'調用的順序。如果前者是第一個,那麼後衛將在路由後收到發出的身份驗證狀態,這將解釋您所看到的行爲。 – cartant

+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觀察到在不觸發對我也。

+0

如果'auth' observable沒有發射任何東西,我會建議[提出問題](https://github.com/angular/ angularfire2/issues),因爲'AngularFireAuth' observable是一個['ReplaySubject',緩衝區大小爲1](https://github.com/angular/angularfire2/blob/master/src/auth/auth.ts#L30 -L35),所以它應該發射一個值。 – cartant

+1

已經有一個問題:https://github.com/angular/angularfire2/issues/496 – rockwotj

+0

感謝這個例子,如果!auth雖然不會返回false嗎? –