your recipe card header background

    Angular Preload Network Strategy

    0

    0

    Jose Romero

    Angular TypeScript Recipes

    This code uses the hasGoodConnection() method to determine if the route should be preloaded. The method checks to see if the connection to the web browser is good. If the connection is good, the load() method is called. Otherwise, the EMPTY Observable is returned.

    Library: angular

    Shortcut: angular.preload.network

    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.