Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 multiple routing module

I'm new in Angular 5 and trying to build an app with client side and admin side. So I did some search and made this:

AppRoutingModule

const appRoutes: Routes = [
    {
        path: '',
        loadChildren: 'app/website/public.module#PublicModule'
    },
    {
        path: 'admin',
        loadChildren: 'app/admin/admin.module#AdminModule'
    }
];

@NgModule({
    imports: [RouterModule.forRoot(appRoutes)],
    exports: [RouterModule]
  })
  export class AppRoutingModule { }

PublicRoutingModule

const PUBLIC_ROUTES: Routes = [
    {
        path: '',
        component: HomeComponent,
    }
];

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

AdminRoutingModule

const ADMIN_ROUTES: Routes = [
    {
        path: '',
        component: DashboardComponent,
        data: {
            title: 'Dashboard'
        },
        children: [

        ]
    }
];

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

And I have imported AppRoutingModule in AppModule, and also imported PublicRoutingModule in PublicModule, also imported AdminRoutingModule in AdminModule.

When I run the app, there is no errors but the HomeComponent is not been rendered initially. Can anyone tell what's the problem here? Thank you.

like image 218
Maher Alhamod Avatar asked Aug 10 '26 01:08

Maher Alhamod


1 Answers

For lazy load module, I think you should add components' declarations to their own router module.

Example for PublicRoutingModule(same for AdminRoutingModule)

const PUBLIC_ROUTES: Routes = [
  {
    path: '',
    component: HomeComponent,
  }
];

@NgModule({
  declarations: [ HomeComponent ],                       // add declaration
  imports: [RouterModule.forChild(PUBLIC_ROUTES)],
  exports: [RouterModule]
})
export class PublicRoutingModule { }

BTW, while debugging routing problems, you should enable tracing to see what really happened during navigation.

@NgModule({
  imports: [RouterModule.forRoot(appRoutes, { enableTracing: true })],
  exports: [RouterModule]
})
export class AppRoutingModule { }
like image 103
Pengyy Avatar answered Aug 13 '26 03:08

Pengyy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!