Search code examples
angularangular-routing

How to restrict unwanted routes in angular cli?


I have set up the routing modules in my angular 8 application using lazy loading. I have set up multiple routing modules. In my authentication routing module, I set a path for /auth/login. However /login also redirects to that same component. How can I restrict this routing?

App-routing.module

const routes: Routes = [
  {
    path: "auth",
    loadChildren: "./authentication/authentication.module#AuthenticationModule"
  },
  {
    path: "user",
    loadChildren: "./user/user.module#UserModule"
  },
  {
    path: "**",
    redirectTo: "auth/login"
  }
];

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

Authentication-routing.module

const routes: Routes = [
  {
    path: "login",
    component: LoginPageComponent
  }
];

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

I expected to load the login component only when I go to the /auth/login route, but it's also loading when I go to the /login route without redirecting.

Here is the sample project on stackblitz : https://stackblitz.com/edit/angular-qor5kr


Solution

  • Actually, this happens because you redirect “all other routes” (path: ‘**’) to auth/login. So the problem is not exactly in /login route.

    If you want to restrict the /login path only - create separate component for it.

    Also, you can put a Guard on path: ** route and implement appropriate redirects. Smth like this:

    // routes
      {
        path: "**",
        redirectTo: "auth/login",
        canActivate: [AuthGuard]
      }
    
    // Guard
    import { Injectable } from '@angular/core';
    import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
    
    @Injectable({
      providedIn: 'root',
    })
    export class AuthGuard implements CanActivate {
      canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): boolean {
    
        if (state.url === '/login') {
            // Handle redirect here
        }
        return true;
      }
    }
    

    UPDATE

    After examine the Stackblitz example I've figured out what's the problem. You have included lazy loaded AuthenticationModule directly into AppModule module. That caused the artifacts. You should remove it

    @NgModule({
      imports:      [ 
        BrowserModule, 
        // AuthenticationModule, <= It's lazy loaded and should not be included
        AppRoutingModule
        ],
      declarations: [ AppComponent ],
      bootstrap:    [ AppComponent ]
    })
    export class AppModule { }
    

    See the corrected example here.