Angular Router: Preloading Modules

yotube
0

The issue with lazy loading, of course, is that when the user navigates to the lazy-loadable section of the application, the router will have to fetch the required modules from the server, which can take time.


To fix this problem we have added support for preloading. Now the router can preload lazy-loadable modules in the background while the user is interacting with our application.



Enabling Preloading: To enable preloading we need to pass a preloading strategy into forRoot.

imports: [RouterModule.forRoot(ROUTES, {preloadingStrategy: PreloadAllModules})]



The latest version of the router ships with two strategies: preload nothing and preload all modules, but you can provide you own. And it is actually a lot simpler that it may seem.

 Say we want to preload all the modules. Rather, we would like to say explicitly, in the router configuration, what should be preloaded.

[

  {

    path: 'moduleA',

    loadChildren: './moduleA.module',

    data: {preload: true}

  },

  {

    path: 'moduleB',

    loadChildren: './moduleB.module'

  }

]



Custom Preloading Strategy:

export class PreloadSelectedModulesList implements PreloadingStrategy {

  preload(route: Route, load: Function): Observable<any> {

    return route.data && route.data.preload ? load() : of(null);

  }

}




Reference : https://vsavkin.com/angular-router-preloading-modules-ba3c75e424cb

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top