I am writing my first Angular App today. Now i want to check the connection to a Server. If its offline, a Screen Should appear that says something like "Youre offline, but you neet a Connection". I have a JavaScript Function that is doing this very good. But right now, I can only check my Connection Status when i click a specific Button. But I want to check the Connection constantly, so if the Connection shuts down, the Screen appears instantly.
I am programming since 2 years now and in the past i heard the sentence "dont use infinite loops" or "never use infinite loops" etc. very often.
My Question is, would it be okay to use an infinite loop in this situation? Or is there another workaround?
My Code is pretty Simple:
var isOnline;
function testIfOnline() {
if(navigator.onLine) {
if (!isOnline) {
hideConnectionView();
}
isOnline = true;
} else {
if (isOnline) {
console.log("Die Verbindung zum Server wurde unterbrochen!");
} else {
console.log("Es konnte keine Verbindung zum Server aufgebaut werden!");
}
isOnline = false;
//Restlicher Code:
showConnectionView();
}
}
Not okay :D Calling a function endlessly is in this case not needed and overkill because there are events.
consider this:
import {fromEvent, merge} from 'rxjs'
merge(
fromEvent(window, 'online'),
fromEvent(window, 'offline'),
).subscribe(
() => {
const condition = navigator.onLine ? "online" : "offline";
console.log(condition);
}
)
EDIT: To combat the fact that this does not work when unplugging the machine we can extend it like this:
import { interval, merge, fromEvent } from 'rxjs';
import { mapTo } from 'rxjs/operators';
merge(
fromEvent(window, 'online'),
fromEvent(window, 'offline'),
interval(1000),
).pipe(
mapTo(navigator.onLine),
).subscribe(
online => {
const condition = navigator.onLine ? "online" : "offline";
console.log(condition);
}
)