Search code examples
angularangular2-routing

Lazy Loading results in ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment:


I implement lazy loading and result into this error. I have seen many post and none of them are giving the solution.

How to reproduce:

  1. Go to https://stackblitz.com/edit/angular-sxmpj8
  2. Click on orders tab
  3. Click Test

Expected: It opens Test component Actual: It results into "Uncaught (in promise): Error: Cannot match any routes. URL Segment:" error

I am trying to lazy load the orders module which has two components orders and test. The orders route is working fine but the test component route throws error.

The application is at https://stackblitz.com/edit/angular-sxmpj8

At orders-routing.module.ts the routes are defined as below:

    const routes: Routes = [
  {
    path: '',
    component: OrdersComponent,

    children: [
      { path: 'test', component: TestComponent
  }]
  }
];

The routes at app-routing.module.ts are defined as below.

const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  },
  {
   path: 'orders',

   // Tried this also
   // loadChildren:  './orders/orders.module#OrdersModule'
    loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
  },
  {
    path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];

In orders.component.ts file I have an entry

<button routerLink="/test">Test</button>

Clicking this result into error

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'test' Error: Cannot match any routes. URL Segment: 'test'


Solution

  • There are two problems:

    1. Because your test component is setup as a child route, you need a module-level <router-outlet> so that the Angular router knows where to render your test component.
    2. On your "test" button, you need to specify the entire route (including /orders).

    I forked your stackblitz so you can see it working here => https://stackblitz.com/edit/angular-sxmpj8-q9xzzv