Preloading modules in Ionic v4

A small delay

Problems

Without preloading
With preloading a specific page, the modules were loaded but in the meantime as the others
Preloading the modules of the detail page after a delay

Solution

import {PreloadingStrategy, Route} from '@angular/router';

import {Observable, of} from 'rxjs';
import {Injectable} from '@angular/core';

export interface RouteToPreload {
routePath: string;
route: Route;
load: Function;
}

@Injectable({
providedIn: 'root'
})
export class AppRoutingPreloaderService implements PreloadingStrategy {

private routesToPreload: RouteToPreload[] = [];

constructor() {
}

preload(route: Route, load: Function): Observable<any> {
if (route.data && route.data.preload) {
this.routesToPreload.push({
routePath: route.path,
route: route,
load: load
});
}

return of(null);
}

preloadRoute(path: string): Promise<void> {
return new Promise<void>((resolve) => {
if (this.routesToPreload &&
this.routesToPreload.length > 0) {
const routeToPreload: RouteToPreload =
this.routesToPreload.find(
(filterRouteToPreload: RouteToPreload) =>
filterRouteToPreload.routePath === path);

if (routeToPreload) {
routeToPreload.load();
}
}

resolve();
});
}
}
const routes: Routes = [
{
path: 'main',
loadChildren: './pages/main.module#MainPageModule'
},
{
path: 'detail',
loadChildren: './pages/detail.module#DetailPageModule',
data: {preload: true}
}
];

@NgModule({
imports: [RouterModule.forRoot(routes, {preloadingStrategy: AppRoutingPreloaderService})],
exports: [RouterModule]
})
export class AppRoutingModule {
}
@Component({
selector: 'app-main',
templateUrl: './main.page.html',
styleUrls: ['./main.page.scss'],
})
export class ItemsPage {

constructor(private routingService: AppRoutingPreloaderService) {}
async ionViewDidEnter() {
await this.routingService.preloadRoute('details');
}
}
Preloading the modules of the detail page after the main page did entered

Freelancer by day | Creator of DeckDeckGo by night | Organizer of the Ionic and IndieHackers Zürich Meetup

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store