Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy Load to route other than empty route in Angular 2

I have my app-routing.module.ts as follow:


    import { NgModule } from '@angular/core';
    import {
        Routes,
        RouterModule
    } from '@angular/router';

    const routes: Routes = [
        {
            path        : 'reset', 
            loadChildren: 'app/auth/reset-password-form/reset-password-form.module#ResetPasswordFormModule'
        },
        {
            path        : 'verify',
            loadChildren: 'app/auth/verify-user-form/verify-user-form.module#VerifyUserFormModule'
        },
        {
            path        : '404',
            loadChildren: 'app/route-not-found/route-not-found.module#RouteNotFoundModule'
        },
        {
            path        : '',
            pathMatch   : 'full',
            loadChildren: 'app/landing-page/landing-page.module#LandingPageModule'
        },
        {
            path      : '**',
            redirectTo: '/404'
        },

    ];

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

When I navigate to the localhost:4200, it will load the landing-page.module properly, however, when I entered localhost:4200/reset or localhost:4200/verify or localhost:4200/404, it will not load the relevant module, instead, it loaded landing-page.module automatically.

How can I solve this problem?

like image 419
ljieyao Avatar asked May 19 '17 09:05

ljieyao


2 Answers

You have to add Routes to your childmodule

  const routes: Routes = [
  { path: '', component: ResetComponent}
  ];
  const ROUTES: ModuleWithProviders = 
  RouterModule.forChild(routes);

and import ROUTES in child module(ResetModule)

@NgModule({
 imports: [
    CommonModule,
    ROUTES,
    ],
 declarations: [ResetComponent],
 exports: [ResetComponent]
})
like image 149
Neeraj Goswami Avatar answered Sep 28 '22 01:09

Neeraj Goswami


This problem might happen because of the imports you have added in imports:[ ] of AppModule (or any other module file).

Make sure to remove all the lazily loaded modules from the imports array.

for eg: I have three modules named:HomeModule, ProfileModule and SettingsModule. if HomeModule is eagarly loaded and ProfileModule and SettingsModule are lazily loaded, then imports:[] of AppModule(app.module.ts) should look like this:

imports:[HomeModule] and it shouldn't include ProfileModule or SettingsModule because they will be loaded automatically during runtime.

like image 28
Naresh Avatar answered Sep 28 '22 03:09

Naresh