Detect Internet Connection in Angular Application
In this tutorial, I will show you how we can detect internet connectivity status in an Angular Application. By connectivity I mean, check if you are online or offline.
This feature is important in application where you might need to switch to offline mode when the internet goes off and save the work locally. Later the local copy can be updated to the cloud once the connection comes back on.
To make this easy we will use a module called ng-connection-service.
Let’s start by setting up an Angular app as usual.
To check if everything was setup correctly by the angular-cli run
You should see Tour Of Heroes running on http://localhost:4200
Now let’s install our module.
npm i ng-connection-service --save
This module exposes a service which we can use to detect the connection.
Let’s import the service into our component file as shown below.
...
import { ConnectionService } from 'ng-connection-service';
....
Now we can instantiate our service and add the piece of code that will do the magic. Below is the entire component file.
import { Component } from '@angular/core';
import { ConnectionService } from 'ng-connection-service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'connectionDetector';
status = 'ONLINE'; //initializing as online by default
isConnected = true;
constructor(private connectionService:ConnectionService){
this.connectionService.monitor().subscribe(isConnected => {
this.isConnected = isConnected;
if(this.isConnected){
this.status = "ONLINE";
} else {
this.status = "OFFLINE"
}
alert(this.status);
});
}
}
Run the app using ng serve
.Now to test our app, if you are connected to the internet you will have to disconnect it. Upon which you will get an alert stating the app is offline. Similarly when you connect it back on it will notify you that its back online.

Conclusion
Thus in this
6 comments
Leave a Comment
Not working
Is there any error in console?
Sorry, tried but got error. Please check.
this.connectionService.monitor().subscribe(isConnected => {
}
in this part isConnected => ,this creates error.
Hi steffy,
This is a bit of an old article, your comment has bought it to notice, I’ll check if there is an issue will update it.
replace isConnected => to isConnected =>
Sweet piece of code, loving it.
Only issue I have is it doesn’t check connection when the app initializes, it waits until i disable/enable the connection.
I would like for the code to check connection when the app starts, putting it in ngOnInit or constructor isn’t doing the trick 🙁