- I am using lazy loading for modules. But when the user navigates to the lazy loaded module route, it takes a couple of seconds to load the module.
- So I use a custom preloading strategy with 20 second time delay. When I serve the application using "ng serve". Everything works fine. My website loads fast, lazy loaded module loads after 20 seconds, and there is no delay when the user navigates to the lazy loaded module route.
- BUT When I serve the application using angular universal command "npm run dev:ssr", everything goes bad. Nothing loads until 20 seconds. My app takes more than 20 seconds to load every time. The amount of delay I put to delay preload, is applied to the initial load.
app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import {CustomPreloadingStrategyService} from './core/services/custom-preloading-strategy.service';
const routes: Routes = [
{
path: 'quick-links',
data: {preload: true, delay: 20000},
loadChildren: () => import('./modules/quick-links/quick-links.module').then(m => m.QuickLinksModule)
}
];
@NgModule({
imports: [RouterModule.forRoot(routes, {
initialNavigation: 'enabled',
scrollPositionRestoration: 'enabled',
preloadingStrategy: CustomPreloadingStrategyService
})],
exports: [RouterModule]
})
export class AppRoutingModule { }
custom-preloading-strategy.service.ts
import { Injectable } from '@angular/core';
import { Observable, of, timer } from 'rxjs';
import { map } from 'rxjs/operators'
import { PreloadingStrategy, Route } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class CustomPreloadingStrategyService implements PreloadingStrategy {
preload(route: Route, loadMe: () => Observable<any>): Observable<any> {
if (route.data && route.data['preload']) {
var delay:number=route.data['delay']
console.log('preload called on '+route.path+' delay is '+delay);
return timer(delay).pipe(
map( _ => {
console.log("Loading now "+ route.path);
return loadMe() ;
}));
} else {
console.log('no preload for the path '+ route.path);
return of(null);
}
}
}