Home > other >  How to show a custom component when there's no internet connection
How to show a custom component when there's no internet connection

Time:10-19

I would like to show a custom componente that I already created when there's not internet connection.

What do I have until now:

  1. A custom component to show when there's not internet connection.
  2. A HttpInterceptor to check my internet connection status.
import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpErrorResponse,
  HttpResponse
} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class ServiceInterceptor implements HttpInterceptor {

  constructor() { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    req = req.clone(
      {
        setHeaders: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      }
    )
 
    const obs = next.handle(req);
 
    if (!window.navigator.onLine) {
      // Handle offline error
      // This message is printing correctly :D
      console.log("no internet connection");
      
      return;
    }
    
    obs.toPromise().catch((error) => {
      console.log(error.message);
    });
    return obs;
 }
} 


  1. A simple service to consume.
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(private httpClient: HttpClient) { }

  public sendGetRequest(){
    return this.httpClient.get('https://jsonplaceholder.typicode.com/todos/1');
  }
} 
  1. My home component where I consume my service.
import { DataService } from '../data.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  products = [];

  constructor(private dataService: DataService) { }

  ngOnInit() {

    this.dataService.sendGetRequest().subscribe((data: any[])=>{
      console.log(data);
      this.products = data;
    })  
  }

}

Everything is working properly when there's internet connection.

But How can I say to my HomeComponent theres not internet?

I dont want to check my internet status in every component I have. Thats why I checked that on httpInterceptor file.

CodePudding user response:

You could route to your dedicated route if there is no internet such as this

  if (!window.navigator.onLine) {
      // Handle offline error
      // This message is printing correctly :D
      console.log("no internet connection");
      // Save the current route state
      this.router.navigateByUrl('no-internet')
      return;
    }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

You could also make use of a service together with a behavioral subject

  1. Connectivity Service

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';  

@Injectable({
  providedIn: 'root'
})
export class ConnectivityService {

  isOnline = new BehaviorSubject();  
  constructor() { }
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  1. Interceptor

@Injectable()
export class ServiceInterceptor implements HttpInterceptor {

  constructor(private connectivityService: ConnectivityService) {}

  intercept(req: HttpRequest < any > , next: HttpHandler): Observable < HttpEvent < any >> {
    req = req.clone({
      setHeaders: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    })

    const obs = next.handle(req);

    if (!window.navigator.onLine) {
      // Handle offline error
      // Update Online status
      this.connectivityService.isOnline.next(false)
      return;
    }

    obs.toPromise().catch((error) => {
      console.log(error.message);
    });
    return obs;
  }
}
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  1. Then in your Home component

import {
  DataService
} from '../data.service';
import {
  ConnectivityService
} from 'connectivityService'
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  products = [];

  constructor(
    private dataService: DataService,
    private connectivityService: ConnectivityService) {}

  ngOnInit() {

    this.connectivityService.isOnline.subscribe(isOnline => {
      if (isOnline) {
        // Your Logic
      }
    })

    this.dataService.sendGetRequest().subscribe((data: any[]) => {
      console.log(data);
      this.products = data;
    })
  }

}
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related