angular2 全局路由守卫_如何使用AngularFire2做一个路由守卫,等待身份验证检查

I want my auth guard to wait until I get the auth back from firebase before it reroutes me. Currently, the auth guard check inits first.

I need to make it async in the canActivate, or only populate the canActivate after called.

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;

}

}

});

}

So how can I make the AuthGuard's canActivate wait for an async boolean?

And how do I pass it to the AuthGuard's canActivate() function?

解决方案

It was answer in this issue post on Github.

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 | Promise | boolean {

return this.auth.afAuth.authState

.take(1)

.map(authState => !!authState)

.do(authenticated => {

if (!authenticated) {

this.router.navigate(['login']);

}

});

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值