我有一个路由保护程序,用于检查用户当前是否已登录:
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
,但我不确定如何在可观察的情境中这样做。
答案 0 :(得分:2)
我不确定您的方法是否有效,但作为一种解决方法,如果getLoginStatus()返回false,您只需在LoggedInGuard中调用this.router.navigate(['/login'])
。