All files / interceptors pwa-offline.interceptor.ts

100% Statements 8/8
100% Branches 4/4
100% Functions 2/2
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29                            1x 4x   4x     2x 2x 1x 1x   1x      
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { NEVER, Observable } from 'rxjs';
 
import { NAVIGATOR } from '../providers/navigator.provider';
 
/**
 * PWA offline interceptor.
 * Redirects to a dedicated view when the app goes offline.
 */
@Injectable({
  providedIn: 'root',
})
export class AppPwaOfflineInterceptor implements HttpInterceptor {
  private readonly navigator = inject(NAVIGATOR);
 
  private readonly router = inject(Router);
 
  public intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    const routeLoaded = this.router.url.includes('offline');
    if (!this.navigator.onLine && !routeLoaded) {
      void this.router.navigateByUrl('/offline');
      return NEVER;
    }
    return next.handle(req);
  }
}