Angular 2 RC4 Route Guards服务注入

时间:2016-07-20 16:57:58

标签: angular routes

我在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.isLoggedIntrue。但是,当重定向到仪表板时,会触发Guard,在其中,authenticationService.isLoggedInfalse

我确定我只是在依赖注入中遗漏了一些内容,但我无法弄明白,也看不出我实际在做什么与教程/文档资料。

1 个答案:

答案 0 :(得分:5)

神圣的废话,我刚刚得到它。在我的MainComponent中将身份验证服务声明为提供程序,因为我已经在bootstrap中将其声明为提供程序,因此创建了一个单独的服务实例。我在MainComponent中取出了提供者对它的引用,现在一切正常!!