Here is a small and easy Angular application to check if you are connected to Internet or not!
First thing you need to do is install a package called ng-connection-service in your angular application. Lets see how do we do that.
Create a new Angular application from the CLI using
ng new InternetTest
Install the ng-connection-service package inside the application from the CLI using:
npm install ng-connection-service — save
Once the packages the installed, go to package.json to check if it has been successfully installed.
Inside package.json, you should see,
https://thepracticaldev.s3.amazonaws.com/i/gkk7naosmjxdwtvh9bmc.png
Now that your required packages are installed, go to the component.ts file and import your Connection service like:
import {ConnectionService} from ‘ng-connection-service’;
Let us finally inject the service inside the component. If you are familiar with service, you’d know that to inject a service, we go to the constructor of the component class and inject it as follows:
constructor(private ConnectionService: ConnectionService){
});
To add the functionality of checking the internet connectivity, we use the service’s functions and toggle the value of isConnected property which is initialized to be true by default and the status property initialized to be ‘ONLINE’ by default. See the code below:
https://gist.github.com/NishuGoel/6bba8594c1424327aee172365bf4f75f
Now we finally alert the status of the connection inside the component class and the completed component looks like this:
https://gist.github.com/NishuGoel/cda15ca29331e6af9edb5dce24c8cb9d
Your component html looks like:
https://gist.github.com/NishuGoel/adb00727c2e1a20ae03033f21bb58159
This is how the result looks like:
https://thepracticaldev.s3.amazonaws.com/i/a3elykc5jdqcq2m1jrzk.gif
The demo has been put up on Stackblitz as well.
Find it here:
Top comments (1)
Here is a detailed explanation - techyhunger.com/internet-connectio...