How to handle connection loss page in Angular 7?
After a little bit of search, and with help of @AlokeT's answer. I got a solution to this problem.
@AlokeT's suggestion is showing connection loss page as soon as the user lost his/her network. but my requirement is to show that connection loss page while he/she tries to navigate to another page.
And In this answer, I just added, that missing part.
For that, I just update that isNetworkStopped
flag from Guard, and because every CanActivate guard executes before navigation starts. So connection lost component would show while the user changing the path.
There is a code of NetworkService
which I'm using in NetworkGuard,
@Injectable({providedIn: 'root'})
export class NetworkService {
online: boolean;
isNetworkStopped = false;
constructor() {
this.online = window.navigator.onLine;
fromEvent(window, 'online').subscribe(e => {
this.online = true;
});
fromEvent(window, 'offline').subscribe(e => {
this.online = false;
});
}
}
Here in above code I just added a flag isNetworkStopped
. And updated that flag from NetworkGuard
, means while the user tries to navigate to next page and found no network.
And also removed navigation from NetworkGuard.
See my below, updated code of NetoworkGuard
@Injectable({providedIn: 'root'})
export class NetworkGuard implements CanActivate {
constructor(private network: NetworkService) {
}
canActivate(next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (this.network.online) {
return true;
}
this.network.isNetworkStopped = true;
return false;
}
}
And based on that flag I managed to show ConnectionLost component.
For that ConnectionLost
component is added on condition based to root component's template.
app.component.html
<router-outlet *ngIf="!networkService.isNetworkStopped"></router-outlet>
<app-connection *ngIf="networkService.isNetworkStopped"></app-connection>
And from ConnectionLost component, if the user clicks on the reload button. By checking network connection I updated isNetworkStopped
flag of NetworkService
.
I don't know is it the right solution or not for you but what I did in my project is following.
app.component.ts
constructor(){
this.onlineOffline = Observable.merge(of(navigator.onLine),
fromEvent(window, 'online').pipe(map(() => true)),
fromEvent(window, 'offline').pipe(map(() => false))
);
}
app.component.html
<ng-container *ngIf="onlineOffline | async; then thenTemplate; else elseTemplate"></ng-container>
<ng-template #thenTemplate>
<router-outlet></router-outlet>
</ng-template>
<ng-template #elseTemplate>
<app-no-network></app-no-network>
</ng-template>
Let me know if it is working the way you need to implement it or not.