私はルートガードの角度2で問題が発生しています。ガードが私の認証サービスの別のインスタンスを取得しているようです。角2 RC4ルートガードのサービスインジェクション
私は角のドキュメントと同様に、セットアップに私のガードをしようとしています:
ガード:
@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
]);
ログインルート:authenticationSerivce.isLoggedIn
がtrue
あるLoginComponent
のlogin()
、で
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
];
。ただし、ダッシュボードへのリダイレクトが発生すると、Guardが起動され、その内部でauthenticationService.isLoggedIn
はfalse
になります。
私は依存性注入で何かが欠落していると確信していますが、実際に行っていることとチュートリアル/ドキュメンテーションとの違いは分かりません。
ブートストラップ機能を表示します。 – micronyks
私はそれらをOPに追加しました –
今はすべてが良いようです。それをキャッチするのは難しいです。 – micronyks