Search code examples
angulartypescriptlazy-loadingangular-routing

Lazy Loading Router Angular 6


Got some troubles with Lazy Loading. All urls shows me empty pages.

Structure:

- app.module.ts
- modules
   - router.module.ts
- scenes
   - dashboard
      - dashboard.module.ts
      - router.module.ts

I have

imports: [
    RoutingModule,
]

in app.module.ts

routing.module.ts:

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

const routes: Routes = [
    {
        path: 'dashboard',
        loadChildren: '../scenes/dashboard/dashboard.module#DashboardModule'
    }
];

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

Notice that i have '../scenes' because it is in different folders with app.module.ts.

dashboard.module.ts:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DashboardRoutingModule } from './routing.module';
import { DashboardComponent } from './dashboard.component';
@NgModule({
    imports: [
        CommonModule,
        DashboardRoutingModule
    ],
    declarations: [DashboardComponent]
})
export class DashboardModule { }

routing.module.ts (in dashboard):

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DashboardComponent } from './dashboard.component';


const routes: Routes = [
    {
        path: '',
        component: DashboardComponent,
        children: [
            { path: 'transactions', loadChildren: './transactions#TransactionsModule' },
        ]
    }
];

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

Checked html-code and I have empty router-outlet so seems like even dashboard.component wont load.

Also is it possible to make it work with using index.ts files. I mean will it work with this?

{ path: 'transactions', loadChildren: './transactions#TransactionsModule' }

Transactions is a folder with index.ts file that exports all data from module:

export * from './transactions.module';

ERROR:

GET http://localhost:4200/dashboard/runtime.js net::ERR_ABORTED 404 (Not Found)

SOLUTION:

I had component with name main and loadChildren: './main#MainModule' and name of generated chunk was main.js but it already exists by default.


Solution

  • It seems that your code is good. How about your router-outlet directives? You mast have one in your app.component.html and one in your dashboard.component.html

    I have a similar example at my github repo. It has a full architecture starter: https://github.com/dedd1993/ngx-admin

    enter image description here

    enter image description here