【发布时间】:2016-11-24 00:00:45
【问题描述】:
我在使用 Angular 2 中的 Route Guards 时遇到问题。看来 Guard 正在获取我的身份验证服务的单独实例。
我正在尝试设置类似于 Angular 文档的防护:
守卫:
@Injectable()
export class AuthenticationGuard implements CanActivate {
constructor(private router:Router,
private authenticationService:AuthenticationService) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.authenticationService.isLoggedIn) {
return true;
}
this.router.navigate(['/login']);
return false;
}
}
服务:
@Injectable()
export class AuthenticationService {
isLoggedIn:boolean = false;
login() {
return Observable.of(true).delay(1000).do(val => this.isLoggedIn = true);
}
logout() {
this.isLoggedIn = false;
}
}
登录:
export class LoginComponent {
constructor(private router:Router,
private authenticationService:AuthenticationService) {
}
login() {
//TODO: Flesh out actual authentication
this.authenticationService.login()
.subscribe(() => {
if (this.authenticationService.isLoggedIn) {
this.router.navigate(["/dashboard"]);
}
});
}
引导程序:
import {bootstrap} from "@angular/platform-browser-dynamic";
import {RouterConfig, provideRouter} from "@angular/router";
import {HTTP_PROVIDERS} from "@angular/http";
//Components
import {MainComponent} from "./main/main.component";
//Routes
import {LoginRoutes, AUTHENTICATION_PROVIDERS} from "./routes/login.routes";
import {DashboardRoutes} from "./routes/dashboard.routes";
import {AdministrationRoutes} from "./routes/administration.routes";
const routes: RouterConfig = [
...LoginRoutes,
...DashboardRoutes,
...AdministrationRoutes
];
//Providers
const ROUTE_PROVIDER = [
provideRouter(routes),
AUTHENTICATION_PROVIDERS
];
bootstrap(MainComponent, [
HTTP_PROVIDERS,
ROUTE_PROVIDER
]);
登录路径:
import {RouterConfig} from "@angular/router";
import {AuthenticationGuard} from "../guards/authentication.guard";
import {AuthenticationService} from "../services/authentication.service";
import {LoginComponent} from "../login/login.component";
export const LoginRoutes: RouterConfig = [
{path: "", redirectTo: "/login", pathMatch: "full"},
{path: "login", component: LoginComponent}
];
export const AUTHENTICATION_PROVIDERS = [
AuthenticationGuard, AuthenticationService
];
在LoginComponent 的login() 中,authenticationSerivce.isLoggedIn 是true。但是,当重定向到仪表板时,会触发 Guard,在其中,authenticationService.isLoggedIn 是 false。
我确定我只是在依赖注入中遗漏了一些东西,但我无法弄清楚,也看不出我实际在做什么与教程/文档内容有任何区别。
【问题讨论】:
-
显示你的引导函数。
-
我将它们添加到 OP
-
到目前为止一切似乎都很好。很难抓住它。