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;
        }
      }
      Typescript language logo
      your recipe card header background

      Angular Preload Network Strategy

      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

      0 Comments

        Add Comment

        Log in to add a comment

        Codiga - All rights reserved 2022.