Search code examples
angulartypescriptangular-lazyloading

Angular 12 - Lazy loading path module does'nt work


I have a jobs module which contains various components of my application. I want to do a lazy load of said module, however, it does not work when I try to access through the full path, that is, if I access through the path http://localhost:4200/job/artist it does not work but if I access through http://localhost:4200/#/artist if it works. Any idea why this happens?

lazy-loaded module's routing module

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { Artist } from './components/artist/artist.component';
const routes: Routes = [{
    path: 'job',
    loadChildren: () => import('../jobs/jobs.module').then(m => m.JobsModule)
}];
@NgModule({
    imports: [
        RouterModule.forRoot(routes, {
            useHash: true,
        }),
        BrowserModule],
    exports: [RouterModule]
})
export class LazyRoutingModule { }

jobs-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { Artist } from './components/artist/artist.component';
const routes: Routes = [{
    path: 'artist',component: ArtistComponent,  
}];

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

Solution

  • Instead of this:

    const routes: Routes = [{
        path: 'artist',component: ArtistComponent,  
    }];
    

    try this:

    const routes: Routes = [
      {
        path: '', component: ArtistComponent,
        children: [
          { path: 'artist', component: ArtistComponent, },         
        ]
      }
    

    EDIT @fralejanro improved my answer, and said that we have to put 'job' instead of just '', in order not to always redirect to artist, just with '\job\artist':

    const routes: Routes = [
      {
        path: 'job', component: ArtistComponent,
        children: [
          { path: 'artist', component: ArtistComponent, },         
        ]
      }