I'm trying to create route guard, read a few blogs and Angular 2 official documentation on it. But I still can't make it work.
Here's RouteGuard (I've removed logging logic to be sure that problem is in routing, not in authentication logic.):
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { Router, CanActivate, CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable()
export class RouteGuard implements CanActivate {
constructor() {
var a = 5;
console.log("RouterGuard called");
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
console.log("RouterGuard called");
return true;
}
}
Here i have some routes:
import { RouteGuard } from './common/routeGuard';
import { ClassifiersComponent } from './components/classifiers/classifiers.component';
import { Routes } from '@angular/router';
import { HomeComponent } from './components/home/home.component';
export const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'classifiers', component: ClassifiersComponent, canActivate: [RouteGuard] },
];
And then i pass them in bootstrapper method:
import { RouteGuard } from './app/common/routeGuard';
import { ClassifiersComponent } from './app/components/classifiers/classifiers.component';
import { HomeComponent } from './app/components/home/home.component';
import { routes } from './app/app.routes';
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
providers: [
{ provide: LocationStrategy, useClass: PathLocationStrategy },
{ provide: APP_BASE_HREF, useValue: '/' },
RouteGuard
],
declarations: [
AppComponent,
HomeComponent,
ClassifiersComponent
],
bootstrap: [AppComponent]
})
export class AppModule {}
I'm not sure what is wrong with this all, may be I'm missing something important. From debugging I can tell that it's hitting canActivate() breakpoint, but does not execute console.log, same goes for constructor.
EDIT: Other routes where there is not any route authentication works fine.
EDIT2: I'm using angular/core 2.2.0, angular/router 3.2.0
RouterGuard calledis not being printed to the browser console? - Günter Zöchbauer{ path: '', component: HomeComponent },should be{ path: '', component: HomeComponent, pathMatch: 'full' },if an empty path route doesn't have child routes. - Günter Zöchbauer