Why is the angular router fetching the lazy loaded module at startup?

Asked
Active3 hr before
Viewed126 times

9 Answers

startuprouterloadedangularmodule
90%

In this article we’ve seen various approaches for lazy loading Angular modules and ultimately the components they contain,,The method takes a selector and lazy loads its corresponding module + instantiates it

Example_snippet/controller/utility/_startup.js/ const routes: Routes = [ { . . .
const routes: Routes = [{
      path: '',
      redirectTo: 'home',
      pathMatch: 'full'
   },
   {
      path: 'home',
      loadChildren: './home/home.module#HomeModule'
   },
   {
      path: 'issues',
      loadChildren: './issue-list/issue-list.module#IssueListModule',
   },
   {
      path: 'search',
      loadChildren: './search/search.module#SearchModule'
   }
];
load more v
88%

The files needed for each component are created automatically, For example for the Contact component,All created sources are indicated at the end of the tutorial

Example_snippet/controller/utility/_startup.js/ # Creating modules ng generate. . .
# Creating modules
ng generate module modules / general / contact--routing--module = app
ng generate module modules / general / signin--routing--module = app
ng generate module modules / general / about--routing--module = app

# Creating modules(method 2)
ng g m modules / general / contact--routing--module = app
ng g m modules / general / signin--routing--module = app
ng g m modules / general / about--routing--module = app
load more v
72%

An NgModule requires some special processing to wire it into your app, This processing is handled automatically by UI-Router for Angular when you use the loadChildren property instead of lazyLoad in your future state

Example_snippet/controller/utility/_startup.js/ var mystate = { name: 'messa. . .
var mystate = {
   name: 'messages',
   url: '/messages',
   component: messages,
   lazyLoad: function() {
      return System.import('moment');
   }
}
load more v
65%

Using Angular 8 (or previous versions) you need to write loadChildren: ',/lazy/lazy

Example_snippet/controller/utility/_startup.js/ @NgModule({ imports: [ R. . .
@NgModule({
   imports: [
      RouterModule.forRoot([{
         path: 'lazy',
         loadChildren: () =>
            import('./lazy/lazy.module').then(m => m.LazyModule),
      }, ]),
   ],
})
export class AppModule {}
load more v
75%

In this guide, you'll learn about lazy loading, Lazy loading helps you render an application faster

Example_snippet/controller/utility/_startup.js/ 1$ ng new lazy-loading-demo. . .
1 $ ng new lazy - loading - demo
load more v
40%

In the lazy-loaded module's routing module, add a route for the component,,Import this resolver into your module's routing module

Example_snippet/controller/utility/_startup.js/ content_copy . . .
      content_copy

      const routes: Routes = [{
         path: 'items',
         loadChildren: () => import('./items/items.module').then(m => m.ItemsModule)
      }];
load more v
22%

We define the modules which we want to lazy load, when we define the routes, Starting from the Angular 8, we have a new syntax for lazy loading

Example_snippet/controller/utility/_startup.js/ loadChilden. . .
loadChilden
load more v
60%

As you can see above, thanks to the loadChildren function, we can lazy load the module AuthModule and the Angular routing will automatically import the bundled scripts for that module alone,,As you have seen, lazy loading auxiliary routes is a feature easily enabled by the Angular Router that allows us to ship much better applications both from a UX and a technical perspective

Example_snippet/controller/utility/_startup.js/ ng generate library auth. . .
ng generate library auth
Step 2 continued with // sign in module@NgModule({ . . .
// sign in module@NgModule({  declarations: [SignInComponent],    imports: [        CommonModule,        SignInRoutingModule    ]})export class SignInModule { }// sign in routing module@NgModule({    imports: [        RouterModule.forChild([{            path: '',            component: SignInComponent        }])    ],    exports: [RouterModule]})export class SignInRoutingModule {}
Step 3 continued with const routes: Route[] = [ { . . .
const routes: Route[] = [{
   component: AuthComponent,
   path: '',
   children: [{
      path: 'sign-in',
      loadChildren: () => import('./sign-in/sign-in.module').then(m => m.SignInModule)
   }, {
      path: 'sign-up',
      loadChildren: () => import('./sign-up/sign-up.module').then(m => m.SignUpModule)
   }, {
      path: '**',
      redirectTo: 'sign-in'
   }]
}];
@NgModule({
   imports: [RouterModule.forChild(routes)],
   exports: [RouterModule]
}) export class AuthRoutingModule {}
Step 4 continued with @Component({ selector: 'auth'. . .
@Component({  selector: 'auth',  template: `    <router-outlet></router-outlet>  `})export class AuthComponent {}
Step 5 continued with // Primary Routing outlet<rout. . .
// Primary Routing outlet<router-outlet></router-outlet>// Dialog Routing outlet<router-outlet name="dialog"></router-outlet>
Step 6 continued with const authRoute = { path: 'au. . .
const authRoute = {
   path: 'auth',
   outlet: 'dialog',
   loadChildren: () => import('@auth').then(m => m.AuthModule)
};
const routes: Routes = [authRoute, // other routes];@NgModule({  imports: [RouterModule.forRoot(routes)],  exports: [RouterModule]})export class AppRoutingModule { }
Step 7 continued with <button [routerLink]="[{ out. . .
<button   [routerLink]="[{ outlets: { dialog: ['auth', 'sign-in'] } }]">  Sign In</button><button   [routerLink]="[{ outlets: { dialog: ['auth', 'sign-up'] } }]">  Sign Up</button>
Step 8 continued with @Component({ selector: 'sign-. . .
@Component({  selector: 'sign-in',  template: `    <ng-template #dialog>      <div mat-dialog-title>        Sign In      </div>      <div mat-dialog-content>        <div>          <mat-form-field appearance="outline">            <input type="email" placeholder="Email" matInput />          </mat-form-field>        </div>        <div>          <mat-form-field appearance="outline">            <input type="password" placeholder="Password" matInput />          </mat-form-field>        </div>      </div>      <div mat-dialog-actions>        <button mat-flat-button color="primary">          Sign In        </button>      </div>    </ng-template>  `,  styleUrls: ['./sign-in.component.css'],  changeDetection: ChangeDetectionStrategy.OnPush})export class SignInComponent implements AfterViewInit {  @ViewChild('dialog') template: TemplateRef<any>;  constructor(      private dialog: MatDialog  ) { }  ngAfterViewInit() {    this.dialog.open(this.template, { width: '350px' });  }}
Step 9 continued with ngAfterViewInit() { const r. . .
ngAfterViewInit() {
   const ref = this.dialog.open(this.template, {
      width: '350px'
   });
   ref.afterClosed().subscribe(() => {
      this.router.navigate(['']);
   });
}
Step 10 continued with const urlWithoutAuxiliaryRoute. . .
const urlWithoutAuxiliaryRoute = this.router.createUrlTree(['.'], {
   relativeTo: this.route
}).root.children[PRIMARY_OUTLET].toString();
this.router.navigate([urlWithoutAuxiliaryRoute]);
load more v
48%

A lazy-loaded routed feature module should not be imported by any module, Doing so would trigger an eager load, defeating the purpose of lazy loading

Example_snippet/controller/utility/_router.js/ import { NgModule } from '@ang. . .
import {
   NgModule
} from '@angular/core';
import {
   Routes,
   RouterModule
} from '@angular/router';
import {
   LoginComponent
} from './core/components/login/login.component';

const appRoutes: Routes = [{
      path: '',
      redirectTo: '/login',
      pathMatch: 'full'
   },
   {
      path: 'login',
      component: LoginComponent
   },
   {
      path: 'home',
      loadChildren: './core/core.module#CoreModule',
   },
   {
      path: '**',
      redirectTo: '/login'
   }
];

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