Search code examples
angularangular-routing

Can't get Angular routing to work properly on refresh


So I've got a pretty simple routing situation setup, in which I'm lazy loading modules:

const routes: Routes = [
  {
    path: '',
    loadChildren: './components/top-accounts/top-accounts.module#TopAccountsModule',
  },
  {
    path: 'tags',
    loadChildren: './components/tags/tags.module#TagsModule',
  },
  {
    path: ':accountId/details',
    loadChildren: './components/account-details/account-details.module#AccountDetailsModule',
  },
  { path: '**', redirectTo: '/' }
];

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

However, when I refresh the page, my routing gets messed up and it tries to default to the / route, even though the URL says something like /tags or /accountId1/details and then it will also give me an error about loading chunks or the page is straight up blank with no error

If I'm trying to get the routes to redirect correct on page load AND show the correct urls AND not give me errors about failing to load lazy loaded module chunks, is there something simple I need to do?

I'm currently on Angular 7.2.0


Solution

  • Please try that:

    RouterModule.forRoot(routes, { useHash: true })
    

    instead of this:

    imports: [RouterModule.forRoot(routes)]
    

    that:

    { path: '**', redirectTo: '/', pathMatch: 'full' }
    

    instead of this:

    { path: '**', redirectTo: '/' }
    

    and take a look for more info here:

    Angular2 without hash in the url and Need clarification RouterModule.forRoot([ ABOUT_ROUTE ], { useHash: true })