Search code examples
angularionic-frameworkionic-native

Ionic angular Preload all module only on device


How to use preload all strategy on device and nopreload on browser? we can load all module like this:

imports: [
CommonModule,
RouterModule.forRoot(appRoutes, { preloadingStrategy: PreloadAllModules }),
...
],

This will preload all module in any platform, But i want to prevent preload when running on browser. And it must only preload on device


Solution

  • It is possible with Ionic's Platform and Angular PreloadingStrategy. You need to have a custom preloading strategy. Here is a sample strategy doing what you want.

    import { Injectable } from '@angular/core';
    import { PreloadingStrategy, Route } from '@angular/router';
    import { Observable, of } from 'rxjs';
    import { Platform } from '@ionic/angular';
    
    @Injectable({
        providedIn: 'root'
    })
    export class LocalOnlyPreloadingStrategy implements PreloadingStrategy {
        constructor(private platform: Platform) { }
        public preload(route: Route, fn: () => Observable<boolean>): Observable<boolean> {
            if (this.platform.is('hybrid')) {
                // Running on a device
                return fn();
            }
            // Not running on a device
            return of(false);
        }
    }
    

    You can import and use just like you are using PreloadAllModules in your code.

    imports: [
    CommonModule,
    RouterModule.forRoot(appRoutes, { preloadingStrategy: LocalOnlyPreloadingStrategy }),
    ...
    ],
    providers: [LocalOnlyPreloadingStrategy]
    

    For more information;