Search code examples
angularangular-routingangular8

Angular routing with default as '' route and '**' for 404 not working as expected


In my app-routing.module file, I have some child routes, an empty route for default login page and one '**' route for 404 pages.

Giving the code below

const routes: Routes = [
  {
    path: 'dashboard',
    loadChildren: () => import('<module path>').then(mod => mod.<module name>)
  },
  {
    path: 'customer',
    loadChildren: () => import('<module path>').then(mod => mod.<module name>)
  },
  {
    path: 'user',
    loadChildren: () => import('<module path>').then(mod => mod.<module name>)
  },
  {
    path: '',
    loadChildren: () => import('<module path>').then(mod => mod.<module name>)
  },
  {
    path: '404',
    component: PageNotFoundComponent,
    canActivate: null
  },
  {
    path: '**',
    redirectTo: '/404',
    canActivate: null
  }

];

By using this code, I am not able to go to the 404 page as it will always redirect to the route('') page. I then changed the order of the route and add the empty('') route at the last and then the 404 worked but event the root empty('') URL (http://localhost:4200) redirects to 404 URL. Is there any way that I can keep the empty URL for login and make the 404 work?


Solution

  • To avoid the '' path to redirect at all times:

    {
        path: '',
        loadChildren: () => import('<module path>').then(mod => mod.<module name>)
        pathMatch: 'full'
    }
    

    Also as a suggestion I would leave the '**' path for all unexpected routes to simplify your code:

    {
        path: '**',
        component: PageNotFoundComponent
    }
    

    You can erase the "canActivate" if you're not using guards :)