Search code examples
angularangular-ui-routerangular4-router

Lazy loading feature module not working


I have a app.routing.ts file as below

    import { ModuleWithProviders, NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { AppComponent } from './app.component';
    import { SalesComponent } from './advisory/sales.component';

    const appRoutes: Routes = [
        {
            path:'admin',loadChildren:'app/auth/admin/admin.module#AdminModule'
        },
        {
            path: '',
            redirectTo: '/main',
            pathMatch: 'full'
        },
        {
            path: 'main', component: SalesComponent,
            data: { apptitle: 'main', subtitle: 'main' }
        },

    ];

@NgModule({
    imports: [RouterModule.forRoot(appRoutes, 
        { useHash: true },
        )],
    exports: [RouterModule]
})

export class AppRoutingModule { }

And a feature module admin.module.ts file as below

 import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { AdminComponent } from './admin.component';
    import { RouterModule } from '@angular/router';

    @NgModule({
      imports: [
    CommonModule,
    RouterModule.forChild([{
    path: '',
    component: AdminComponent,
    }
    ]),

    declarations: [AdminComponent]
    })

    export class AdminModule { }

If I hit localhost:4200/#/main in the browser, it is working but if I enter localhost:4200/#/admin or localhost:4200/admin- it refreshes and loads the same main page. Any idea why this may be happening and any suggestions?


Solution

  • Here is a StackBlitz where it works https://stackblitz.com/edit/angular-f568ym?file=src%2Fapp%2Fapp.component.html

    You should use a relative path.

    path:'admin',loadChildren:'./auth/admin/admin.module#AdminModule'

    Also you may have an issue with the routes defined within the AdminModule

    I would change the syntax in the AdminModule to this:

    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { AdminComponent } from './admin.component';
    import { RouterModule } from '@angular/router';
    
    const adminRoutes: Routes = [
      {
          path:'',
          component:AdminComponent,
          pathMatch: 'full'
      }
    ];
    
    @NgModule({
      imports: [
        CommonModule,
        RouterModule.forChild(adminRoutes)
      ],
      declarations: [AdminComponent]
    })
    
    export class AdminModule { }