[Angular 8] Implement a Custom Preloading Strategy with Angular

Preloading all modules is quite an extreme approach and might not always be desirable. For instance, you don't want to preload lazy routes a user might not even have access to. Therefore, in this lesson we're going to have a look at how to define a custom preloading strategy in Angular.

custom-preloader.ts:

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

@Injectable({
  providedIn: 'root'
})
export class CustomPreloader implements PreloadingStrategy {
  preload(route: Route, load: Function): Observable<any> {
    if (route.data && route.data['preload']) {
      return load();
    } else {
      return of(null);
    }
  }
}
import { CustomPreloader } from './custom-preloader';

@NgModule({
  declarations: [AppComponent, HomeComponent],
  imports: [
    BrowserModule,
    MatSidenavModule,
    BrowserAnimationsModule,
    RouterModule.forRoot(
      [
        {
          path: '',
          component: HomeComponent
        },
        {
          path: 'nyan',
          loadChildren: () =>
            import('./nyan/nyan.module').then(m => m.NyanModule),
          data: {
            preload: true
          }
        },
        {
          path: 'about',
          loadChildren: () =>
            import('./about/about.module').then(m => m.AboutModule)
        }
      ],
      {
        preloadingStrategy: CustomPreloader //PreloadAllModules
      }
    )
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}
原文地址:https://www.cnblogs.com/Answer1215/p/11430757.html