Today in the article, we will create a demo app for how to check the internet connection in angular application either it is connected to the system or not. It's a very common requirement to check the internet connection in any web application or mobile application. Implementing such functionalities makes our app more user-friendly.
We might want to show alert "you are online/offille" and show the cached data to load. And whenever connects show the alert to the user. The same task can also be achieved with only javascript only using window.ononline and window.onoffline
events
We will use here a npm package called npm-connection-service. So at first create the basic app with below command.
npm new internet-connection-check
Once angular application is created move to that folder and run the application with ng serve. After that we can see our app over the browser on the link: http://localhost:4200
npm i ng-connection-service --save
This module exposes a service which we can use to detect the internet connection in our system.
Now we will import the service into our component by adding below line in our app.component.ts file.
import { ConnectionService } from 'ng-connection-service'
Once importing the service in our component we will add the code in the class constructor which will do the actual job for showing the alert in our demo when internet connects of disconnets.
Now the app.component.ts will look like:
In the above file we have performed mainly two main task:
1. Injected ConnectionService in Angular component constructor.
2. Subscribed to monitor() method to get notified whenever the internet connection is changed.
Run the app by typing ng serve over terminal, And test the app. Once you disconnect the internet connection then you will get alert of OFFLINE message, Simillarly when you connect the connection back alert will come on browser again of message ONLINE.
So in this demo, We learnt how to check internet connection in angular application.
That’s all for now. Thank you for reading and I hope this demo will be very helpful to understand how to check internet connection in angular application.
Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.
You can download complete code from here. Download Code