我希望我的认证警卫等到我重新安排我之前从firebase返回认证。目前,授权警卫首先进行检查。
我需要在canActivate中使其异步,或者只在调用后填充canActivate。
auth.guard.ts
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService) {
console.log(this.authService.isAuthenticated); // returns false, doesn't async
}
canActivate() {
console.log(this.authService.isAuthenticated); // returns false
return this.authService.isAuthenticated;
}
}
auth.service.ts
...
import { AngularFire,
AuthProviders,
AuthMethods,
FirebaseListObservable,
FirebaseObjectObservable } from 'angularfire2';
...
@Injectable()
export class AuthService {
isAuthenticated: boolean = false;
// the problem is setting it to a bool, need to async it (( but this was from official documentation and Pluralsight tuts__
constructor(
public af: AngularFire,
private _router: Router,
private _route: ActivatedRoute ) {
this.af.auth.subscribe((auth)=>{
console.log('called after after auth guard');
if (auth == null) {
this._router.navigate(['/login']);
} else {
this.isAuthenticated = true;
}
}
});
}
答案 0 :(得分:1)
在Github的this期刊中回答了这个问题。
auth.service.ts:
@Injectable()
export class AuthService {
private _user: firebase.User;
constructor(public afAuth: AngularFireAuth, private db: AngularFireDatabase) {
afAuth.authState.subscribe(user => this.user = user);
}
get user(): firebase.User {
return this._user;
}
set user(value: firebase.User) {
this._user = value;
}
get authenticated(): boolean {
return this._user !== null;
}
}
auth.guard.ts:
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.auth.afAuth.authState
.take(1)
.map(authState => !!authState)
.do(authenticated => {
if (!authenticated) {
this.router.navigate(['login']);
}
});
}
}