lazy loaded states (ocLazyLoad, future states) in modern Angular
Lazy loading is built into the router. loadComponent loads one standalone component, and loadChildren loads a whole file of routes.
Before · AngularJS
$stateProvider.state('reports', {
url: '/reports',
templateUrl: 'reports/reports.html',
controller: 'ReportsCtrl as vm',
resolve: {
deps: function ($ocLazyLoad) {
return $ocLazyLoad.load('reports/reports.module.js');
}
}
});After · Angularexport const routes: Routes = [
{
path: 'reports',
loadComponent: () =>
import('./reports/reports.component').then(m => m.ReportsComponent),
},
{
path: 'admin',
loadChildren: () =>
import('./admin/admin.routes').then(m => m.ADMIN_ROUTES),
},
];
// app.config.ts
provideRouter(routes, withPreloading(PreloadAllModules))What changes
- The bundler splits the code at each dynamic import(), so there is no list of script files to maintain.
- Services used only by a lazy section can be declared in the providers array of its route, which scopes them to that section.
- withPreloading downloads lazy routes in the background after the first render.
Migration tip. The modules the old app loaded with ocLazyLoad already mark its natural sections. Use them as the first cut for your route files, then check that no lazy section depends on code registered by another one.
Related
- $onInit / $onChanges / $onDestroy / $postLink
- $scope.$on('$destroy')
- require (parent controllers)
- ngRoute ($routeProvider, ng-view)
Planning a migration or a micro-frontend platform?
In a 20-minute call you describe your situation and I tell you how I'd approach it. If it isn't worth doing yet, I'll say so.
Message me on LinkedIn