使用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中的操作不會發生。
我會仔細看看你在登錄和警衛中使用的'console.log'調用的順序。如果前者是第一個,那麼後衛將在路由後收到發出的身份驗證狀態,這將解釋您所看到的行爲。 – cartant
對不起,我忘了把我的控制檯輸出,我已經將它添加到問題 –