your recipe card header background

    Angular Network Aware Preload Strategy

    0

    1

    lucycodes42

    Angular snippets for TypeScript

    This file contains a NetworkAwarePreloadStrategy class that implements the PreloadingStrategy interface.

    This class has a preload() method that returns an Observable object. This object will be filled with data if the user has a good connection. The preload() method checks to see if the user has a save data connection by checking the value of the navigator.connection property. If the user has a save data connection, the preload() method will avoid preloading any routes that have the Slow-2g, 2g, 3g, or 4g effectiveType values in the avoidTheseConnections array. If the user does not have a save data connection, the preload() method will preload all routes.

    The hasGoodConnection() method checks to see if the user has a good connection by querying the value of the navigator.connection property. If the user has a good connection, the hasGoodConnection() method will return true . Otherwise, the hasGoodConnection() method will return false .

    Library: angular

    Shortcut: a_preload_network_strategy

    import { Injectable } from '@angular/core';
    import { PreloadingStrategy, Route } from '@angular/router';
    import { Observable, EMPTY } from 'rxjs';
    
    // avoid typing issues for now
    export declare var navigator;
    
    @Injectable({ providedIn: 'root' })
    export class NetworkAwarePreloadStrategy implements PreloadingStrategy {
      preload(route: Route, load: () => Observable<any>): Observable<any> {
        return this.hasGoodConnection() ? load() : EMPTY;
      }
    
      hasGoodConnection(): boolean {
        const conn = navigator.connection;
        if (conn) {
          if (conn.saveData) {
            return false; // save data mode is enabled, so dont preload
          }
          const avoidTheseConnections = ['slow-2g', '2g' /* , '3g', '4g' */];
          const effectiveType = conn.effectiveType || '';
          if (avoidTheseConnections.includes(effectiveType)) {
            return false;
          }
        }
        return true;
      }
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Explore
    • Cookbooks
    • Playground
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.