Reputation: 1289
I am having a strange issue since I updated to angular's latest router(3.0.0-beta.2)
If I execute this code
this._router.navigate(['/login']);
anywhere in my app it works fine except the first time a user navigates to the page, and a redirect is needed for him to log in. No error is thrown, it just simply does not redirect.
Here is my code:
main.ts file:
bootstrap(AppComponent, [APP_ROUTER_PROVIDERS, HTTP_PROVIDERS, ApplicationConfiguration, provide(Http, {
useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions, router: Router, appConfig: ApplicationConfiguration) => new HttpServiceLayer(xhrBackend, requestOptions, router, appConfig),
deps: [XHRBackend, RequestOptions, Router, ApplicationConfiguration]
})]);
app.component.ts:
export class AppComponent {
constructor(private appConfig: ApplicationConfiguration, private _router: Router) {
if (!this.appConfig.isUserLoggedIn()) {
this._router.navigate(['/login']);
}
}
}
export const routes: RouterConfig = [
{ path: 'login', component: LogInComponent },
{ path: 'dashboard', component: DashboardComponent },
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' }
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];
It may be that I am not doing something correct, but this code used to work before the update.
Does any body know why the router would not redirect the user to the log in page?
Any help is appreciated.
Solution: Using a Guard on the dashboard route should do the trick.
export class AppComponent {
constructor() {}
}
export const routes: RouterConfig = [
{ path: 'login', component: LogInComponent },
{ path: 'dashboard', component: DashboardComponent, canActivate: [DashboardGuard]},
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' }
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];
@Injectable()
export class DashboardGuard implements CanActivate {
constructor(private appConfig: ApplicationConfiguration, private _router: Router) {}
canActivate() {
if (this.appConfig.isUserLoggedIn()) { return true; }
this._router.navigate(['/login']);
return false;
}
}
And in main.ts you need to add the DashboardGuard as a provider.
Upvotes: 0
Views: 1507
Reputation: 51
Using a Guard on the dashboard route should do the trick.
export class AppComponent {
constructor() {}
}
export const routes: RouterConfig = [
{ path: 'login', component: LogInComponent },
{ path: 'dashboard', component: DashboardComponent, canActivate: [DashboardGuard]},
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' }
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];
@Injectable()
export class DashboardGuard implements CanActivate {
constructor(private appConfig: ApplicationConfiguration, private _router: Router) {}
canActivate() {
if (this.appConfig.isUserLoggedIn()) { return true; }
this._router.navigate(['/login']);
return false;
}
}
Upvotes: 2