Ich habe ein Problem mit den Route Guards in Angular 2. Es scheint, als ob der Guard eine separate Instanz meines Authentifizierungsdienstes erhält.Angular 2 RC4 Route Guards Service-Injektion
Ich versuche, meine Wache ähnlich Setup der Winkel Dokumentation:
The Guard:
@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;
}
}
Der Service:
@Injectable()
export class AuthenticationService {
isLoggedIn:boolean = false;
login() {
return Observable.of(true).delay(1000).do(val => this.isLoggedIn = true);
}
logout() {
this.isLoggedIn = false;
}
}
Die Anmeldung:
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"]);
}
});
}
Die 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
]);
Die Anmeldung Routen:
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
];
Im LoginComponent
‚s login()
, die authenticationSerivce.isLoggedIn
ist true
. Wenn jedoch die Umleitung zum Dashboard erfolgt, wird der Guard ausgelöst, und darin ist authenticationService.isLoggedIn
false
.
Ich bin sicher, dass ich gerade etwas in der Abhängigkeitsinjektion verpasse, aber ich kann es nicht herausfinden und sehe keinen Unterschied in dem, was ich tatsächlich tue, im Vergleich zu den Tutorial/Dokumentationskram.
Zeigen Sie Ihre Bootstrap-Funktion an. – micronyks
Ich habe sie dem OP –
hinzugefügt. Alles scheint bis jetzt gut zu sein. Schwer, es zu fangen. – micronyks