Search code examples
angularangular-routing

Lazy loading in Angular 6 resulting in Cannot match any routes


I am trying to achieve lazy loading in my Angular app. Here are my routes:

app-routing.module.ts

const routes: Routes = [
  {
    path: '',
    loadChildren: './customer/customer.module#CustomerModule',
    pathMatch: 'full'
  }
];

and in module:

  imports: [RouterModule.forRoot(routes)],

customer-routing.module.ts

export const routes: Routes = [
  { path: '', component: ComparePageComponent },
  { path: 'funds', component: FundSelectionComponent },
  { path: ':service', component: ComparePageComponent },
  { path: '**', component: PageNotFoundComponent },
];

and in module :

imports: [
    RouterModule.forChild(routes)
  ],

Now, I have a logic that will load the /profile page when there are no path params i.e. when the url is '' (this._router.navigate(['', 'profile'])) for which I have already defined a path in my customer module { path: ':service', component: ComparePageComponent }

But, when the app runs, it results in the following error:

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'profile' Error: Cannot match any routes. URL Segment: 'profile' at ApplyRedirects.push../node_modules/@angular/router/fesm5/router.js.ApplyRedirect

Not really sure where I am going wrong.


Solution

  • Your AppRoutingModule just has one route that loads the CustomerModule for the user. But that too on an empty route('').

    But when you navigate the user to the /profile route, Angular is looking for a config corresponding to the 'profile' path in your AppRoutingModule.

    But since it's not able to find it there, it's throwing this error.

    To make Angular look beyond the empty path(''), it needs to use the prefix pathMatch strategy, which is used by default unless you specify it as full.

    You might want to try removing the pathMatch: 'full' from your route config in the AppRoutingModule in order to fix it.