3

So, I'm building an Angular 4 app that I want all routes to be protected (except for the login route of course). I'm trying to use feature modules and feature module routing. So, imagine something like this:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuardService } from './auth/auth-guard.service';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { ProtectedRouteComponent } from './protected-route/protected-route.component';

const routes: Routes = [
  { path: 'login', component: LoginComponent }, // no auth guard for login
  {
    path: '',
    canActivate: [AuthGuardService],
    children: [
      {
        path: '',
        children: [
          { path: 'register', component: RegisterComponent },
          { path: 'protected', component: ProtectedRouteComponent }
        ]
      }
    ]
  }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

, for the root module, and then a users feature module routing config like:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { UsersComponent } from './users.component';

const routes: Routes = [
  { path: 'users', component: UsersComponent }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class UsersRoutingModule {}

What would be the best way to:

  • Keep using feature module routing, and
  • Apply the route guards to the users feature module routing without replicating the canActivate guard? Is there any way I can pass it on to the users feature module routing from the root routing module?

Thanks,
Iraklis

Iraklis Alexopoulos
  • 909
  • 2
  • 14
  • 27

1 Answers1

0

Was looking for the same and the solution I found involves the following steps:

  • Do not import your feature module via app modules
  • Instead import the feature module as part of your app module routes
{
    path: '',
    canActivate: [AuthGuardService],
    children: [
      {
        path: '',
        children: [
          { path: 'register', component: RegisterComponent },
          { path: 'protected', component: ProtectedRouteComponent }
        ]
      },
      {
        path: '',
        children: () => UsersModule
      }
    ]
  }

One thing to consider:

  • Other modules will NOT have access to your UserModule's components and services (until you have visited one of the /users routes)
  • This might not be a problem as your modules might already be well separated
ntziolis
  • 10,091
  • 1
  • 34
  • 50