R
R
Roman Rakzin2022-02-09 19:34:12
Angular
Roman Rakzin, 2022-02-09 19:34:12

How to make smart lazy loading of modules in Angular after switching to a certain route or by values?

How can you implement loading a module in Angular only if the user has moved to a certain route or when a certain event occurs?
And is it possible to register somehow in the route, so that the preload would go on, for example, only if there is a certain criterion, say, an admin person, or something else?

I just did something like this and I want to upgrade the routing. routes

{
    path: 'import-catalog',
    loadChildren: () => import('./pages/import-catalog/import-catalog.module').then(mod => mod.ImportCatalogModule),
    data: {preload: true, preloadAfter: 700},
    canActivate: [AuthGuard]
  }

add a link to the preloading service in app.module

imports: [
    RouterModule.forRoot(routes, {
    preloadingStrategy: CustomPreloadingStrategyService,......

and the service itself

import {Injectable} from '@angular/core';
import {PreloadingStrategy, Route} from '@angular/router';
import {Observable, of, timer} from 'rxjs';
import {map} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class CustomPreloadingStrategyService implements PreloadingStrategy {
preload(route: Route, fn: () => Observable<any>): Observable<any> {
    const loadRoute = (delay) => delay > 0 ? timer(delay).pipe(map(() => fn())) : fn();
    if (route.data && route.data.preload) {
      const delay = route.data.preloadAfter ? route.data.preloadAfter : 0;
      return loadRoute(delay);
    }
    return of(null);
  }
}

Thus, I have modules loaded after the specified milliseconds, but I would like more criteria - to load only if the type myValue=isAdmin, and also to load after certain milliseconds only if the person has switched to a certain route, otherwise do not load.

Maybe this is a "perversion", but for skill and for optimization it would be desirable.
Has anyone done this?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question