gpt4 book ai didi

Angular 2 RC4 Route Guards 服务注入(inject)

转载 作者:太空狗 更新时间:2023-10-29 18:17:09 25 4
gpt4 key购买 nike

我在 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"]);
}
});
}

Bootstrap :

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
];

LoginComponentlogin() 中,authenticationSerivce.isLoggedIntrue。然而,当重定向到 Dashboard 时,Guard 被触发,并且在它内部,authenticationService.isLoggedInfalse

我确定我只是在依赖项注入(inject)中遗漏了一些东西,但我无法弄清楚,也看不出我实际所做的与教程/文档的内容有什么不同。

最佳答案

天哪,我刚刚明白了。在我的 MainComponent 中将身份验证服务声明为提供者是在创建该服务的一个单独实例,因为我已经在 bootstrap 中将其声明为提供者。我在 MainComponent 中取出了对它的提供者引用,现在一切正常!!

关于Angular 2 RC4 Route Guards 服务注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38486517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com