Search code examples
angularangular-routingangular5angular-routerangular-router-guards

canActivate is not working after upgrading to angular 5


I'm upgrading to angular 5 my project and I can't understand how can activate is not working anymore:

//package.json:

dependencies": {
"@angular/animations": "~5.1.3",
"@angular/cdk": "5.0.3",
"@angular/common": "~5.1.3",
"@angular/compiler": "~5.1.3",
"@angular/core": "~5.1.3",
"@angular/flex-layout": "2.0.0-beta.12",
"@angular/forms": "~5.1.3",
"@angular/http": "~5.1.3",
"@angular/material": "5.0.3",
"@angular/platform-browser": "~5.1.3",
"@angular/platform-browser-dynamic": "~5.1.3",
"@angular/router": "~5.1.3",
"@ngx-translate/core": "^9.0.2",
"amazon-cognito-identity-js": "^1.25.0",
"angular-in-memory-web-api": "^0.5.2",
"angular2-highcharts": "^0.5.5",
"core-js": "^2.4.1",
"highcharts-export-csv": "git+https://github.com/highcharts/export-csv.git",
"leaflet": "^1.2.0",
"leaflet-draw": "^0.4.12",
"leaflet.markercluster": "^1.1.0",
"ng2-dnd": "^4.2.0",
"rxjs": "^5.5.2",
"zone.js": "^0.8.14"
},

my routing and module files:

//app.routing
const APP_ROUTES: Routes = [
{
    path: '',
    canActivate: [LoggedInGuard],
    children: [
        {path: '', loadChildren: 'app/myModule/myModule.module#MyModule', pathMatch: 'full'}
    ]
},
{path: '**', redirectTo: ''}
];
//app.module
providers: [
LoggedInGuard 
],

and my routing file in myModule:

myModule.routing

const MYMODULE_ROUTES: Routes = [

   {path: '', component: MyModuleComponent},
];

the problem is LoggedInGuard is never invoked, and I can't understand what are I missing

I add my loggedInGuard function because @Rowel de Guzman comment

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class LoggedInGuard implements CanActivate {
   constructor(private router: Router, private userService: UserService) {
       console.log("constructor");
   }

 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
 console.log("inside canActivate!");
   if (state.url !== '/login') {
  this.router.navigate(['/login']);
  return false;
}

return true;

} }


Solution

  • I found it, the problem was in myModule.routing, I write complete routes instead of relatives, and as it has not canActivate protection it passes.

    Thanks for your time!