Refactor online status tracker.

This commit is contained in:
Spencer Ofwiti 2021-07-01 16:22:27 +03:00
parent 5fcee3dcf9
commit beca2bf7f8
4 changed files with 35 additions and 7 deletions

View File

@ -9,3 +9,4 @@ export * from '@app/_helpers/mock-backend';
export * from '@app/_helpers/read-csv';
export * from '@app/_helpers/schema-validation';
export * from '@app/_helpers/sync';
export * from '@app/_helpers/online-status';

View File

@ -0,0 +1,17 @@
const apiUrls = [
'https://api.coindesk.com/v1/bpi/currentprice.json',
'https://dog.ceo/api/breeds/image/random',
'https://ipinfo.io/161.185.160.93/geo',
'https://randomuser.me/api/',
];
async function checkOnlineStatus(): Promise<boolean> {
try {
const online = await fetch(apiUrls[Math.floor(Math.random() * apiUrls.length)]);
return online.status >= 200 && online.status < 300;
} catch (error) {
return false;
}
}
export { checkOnlineStatus };

View File

@ -1,6 +1,6 @@
<nav class="navbar navbar-dark background-dark">
<h1 class="navbar-brand">
<div *ngIf="noInternetConnection; then offlineBlock; else onlineBlock"></div>
<div *ngIf="online; then onlineBlock; else offlineBlock"></div>
<ng-template #offlineBlock>
<strong style="color: red">OFFLINE </strong>
<img width="20rem" src="assets/images/no-wifi.svg" alt="Internet Disconnected" />

View File

@ -1,4 +1,5 @@
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { checkOnlineStatus } from '@src/app/_helpers';
@Component({
selector: 'app-network-status',
@ -7,21 +8,30 @@ import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class NetworkStatusComponent implements OnInit {
noInternetConnection: boolean = !navigator.onLine;
online: boolean = navigator.onLine;
constructor(private cdr: ChangeDetectorRef) {
this.handleNetworkChange();
}
ngOnInit(): void {}
ngOnInit(): void {
window.addEventListener('online', (event: any) => {
this.online = true;
this.cdr.detectChanges();
});
window.addEventListener('offline', (event: any) => {
this.online = false;
this.cdr.detectChanges();
});
}
handleNetworkChange(): void {
setTimeout(() => {
if (!navigator.onLine !== this.noInternetConnection) {
this.noInternetConnection = !navigator.onLine;
setTimeout(async () => {
if (this.online !== (await checkOnlineStatus())) {
this.online = await checkOnlineStatus();
this.cdr.detectChanges();
}
this.handleNetworkChange();
}, 5000);
}, 3000);
}
}