canActivate初始加载失败而不是按预期重定向

时间:2017-06-21 19:07:33

标签: angular typescript angular2-routing

我有一个路由保护程序,用于检查用户当前是否已登录:

import {Injectable} from "@angular/core"
import {CanActivate} from "@angular/router"

import {Observable} from "rxjs/Observable"
import {UserService} from "./user.service"

@Injectable()
export class LoggedInGuard implements CanActivate {
    constructor (private userService: UserService) {}

    canActivate (): Observable<boolean> {
        return this.userService.getLoginStatus()
    }
}

user.service:

import {Injectable} from "@angular/core"
import {Router} from "@angular/router"

import {Observable} from "rxjs/Observable"
import {AngularFireAuth} from "angularfire2/auth"
import * as firebase from "firebase/app"

@Injectable()
export class UserService {
    private user: firebase.User

    constructor (private router: Router, private afAuth: AngularFireAuth) {
        this.afAuth.authState.subscribe(user => {
            this.user = user
        })
    }

    public login (email: string, password: string) {
        this.afAuth.auth.signInWithEmailAndPassword(email, password).then(user => {
            this.user = user
            this.router.navigateByUrl("/dashboard")
        })
    }
    public logout () {
        this.afAuth.auth.signOut()
    }
    public getLoginStatus (): Observable<boolean> {
        return this.afAuth.authState.map(Boolean)
    }
}

//login的重定向:

{path: "", redirectTo: "login", pathMatch: "full"}

当用户登录时,或者直接导航到//login(前者正确地重定向到后者)时,一切正常。但是,如果我在未登录的情况下尝试导航到受保护的路线,它会将我重定向到/,但之后不再重定向,而是停在空白页面上。

第二次重定向是否有效?或者甚至更好的是警卫直接转到/login,但我不确定如何在可观察的情境中这样做。

1 个答案:

答案 0 :(得分:2)

我不确定您的方法是否有效,但作为一种解决方法,如果getLoginStatus()返回false,您只需在LoggedInGuard中调用this.router.navigate(['/login'])

@see示例:Angular 2 AuthGuard Service with redirect?