Angular 2 CanActivate not working

I am trying to create route protection, read some blogs and Angular 2 official documentation . But I still can't get it to work.

Here's RouteGuard (I removed the logging logic to make sure that the problem is in the routing and not in the 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 several 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 pass them in the bootstrap 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's wrong with this, maybe I missed something important. From debugging, I can say that it removes the canActivate () breakpoint, but does not execute console.log, the same goes for the constructor.

EDIT: Other routes where there is no route authentication work fine.

EDIT2: I am using angular / core 2.2.0, angular / router 3.2.0

+6
source share
1 answer

Upgrade to angular / core 2. 3 .0, angular / router 3. 3 .0 solved this problem, I have no idea why.

-one
source

Source: https://habr.com/ru/post/1013034/


All Articles