In this post, we will learn how to show a toast or snack bar message to the user of the application when there is some network issue or when a user has connected again with the network.
Applicable from Angular 2 to latest versions including 6,7,8,9,10,11 and 12
While using the application if suddenly there is some network issue, it is a good user experience to show a toast or snack bar message to the user that there is some Network issue and the application is offline.
Similarly, when the user is connected back with the network we can display an information message that you connected to the network.
To do this we can use the window
object and use its events to know when an application is offline or online.
We can simply create event handlers as shown below:
// addEventListener version
window.addEventListener('online', (event) => {
console.log("You are now connected to the network.");
});
// ononline version
window.ononline = (event) => {
console.log("You are now connected to the network.");
};
// addEventListener version
window.addEventListener('offline', (event) => {
console.log("You are offline!");
});
// onoffline version
window.onoffline = (event) => {
console.log("You are offline!");
};
Or create a method named handleNetwork()
and use the RxJS fromEvent
method to add subscription to online
and offline
handlers.
The fromEvent()
function creates an Observable that emits events of a specific type coming from the given event target
handleNetwork(){
fromEvent(window,'offline').subscribe(event=>{
console.log('offline');
});
fromEvent(window,'online').subscribe(event=>{
console.log('online');
});
}
Need to call the handleNetwork()
only once when the application initializes like in AppComponent
‘s constructor()
import { Component } from '@angular/core';
import { fromEvent } from 'rxjs';
export interface USER {
isAdmin: boolean;
profileImage: string;
age: number;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
constructor(
) {
this.handleNetwork();
}
handleNetwork() {
fromEvent(window, 'offline').subscribe(event => {
console.log('You are offline');
});
fromEvent(window, 'online').subscribe(event => {
console.log('You are back online');
});
}
}
Instead of logging these messages, you can add Toasts or Snackbar to intimate users while using the application.
Adding Angular Material
Install Material package
Execute the following command to install the Material package
$ ng add @angular/material
Then select options ask while installation
The package @angular/material@12.1.0 will be installed and executed.
Would you like to proceed? Yes
✔ Package successfully installed.
? Choose a prebuilt theme name, or "custom" for a custom theme: Indigo/Pink [ Preview: https://material.angular.io?theme=indigo-pink ]
? Set up global Angular Material typography styles? No
? Set up browser animations for Angular Material? Yes
UPDATE package.json (1157 bytes)
✔ Packages installed successfully.
UPDATE src/app/app.module.ts (990 bytes)
UPDATE angular.json (3485 bytes)
UPDATE src/index.html (568 bytes)
UPDATE src/styles.scss (181 bytes)
Import Required Modules
As we are going to use the Material Snackbar component. Import the MatSnackBarModule
as shown below:
....
import { MatSnackBarModule } from '@angular/material/snack-bar';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
BrowserAnimationsModule,
MatSnackBarModule
],
bootstrap: [AppComponent]
})
export class AppModule { }
Update the AppComponent to show Snack bars as shown below:
import { Component } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { fromEvent } from 'rxjs';
export interface USER {
isAdmin: boolean;
profileImage: string;
age: number;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
constructor(
private _snackBar: MatSnackBar
) {
this.handleNetwork();
}
handleNetwork() {
fromEvent(window, 'offline').subscribe(event => {
this._snackBar.open('You are offline','Dismiss',{
duration:2000
});
});
fromEvent(window, 'online').subscribe(event => {
this._snackBar.open('You are back online','Dismiss',{
duration:2000
});
});
}
}
To test this, you can toggle between the ‘No throttling’ and ‘Offline’ option under the Network tab in Debug mode in Chrome browser.