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 Network Aware Preload Strategy

      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 .

      Shortcut: a_preload_network_strategy

      0 Comments

        Add Comment

        Log in to add a comment

        Codiga - All rights reserved 2022.