Create a Snackbar to check whether a user is online or offline in Angular in a minute!
A small and easy Angular application to check if user is connected to Internet or not with use of Angular material
First of all you have to install a packaged called ng-connection-service. Lets see how do we do that.
Create new Angular application using CLI
ng new Online
Install the ng-connection-service package inside the application from the CLI using:
npm install ng-connection-service — save
Once if you done this process please check your package.json whether it is added or not
You should see something like below,
now, time to install Angular Material into your project using CLI
npm install — save @angular/material @angular/cdk @angular/animations
now, import it in app.component.ts like below:
import {MatSnackBar,MatSnackBarConfig,MatSnackBarHorizontalPosition,MatSnackBarVerticalPosition} from ‘@angular/material’;
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, public snackbar: MatSnackBar){
});
now the time for write logic of checking the internet connectivity. See the code below:
Final result look like:
Here you can see whenever I turned off my wifi connection Snackbar pop up in bottom and show OFFLINE Status.