What I want is that, If the network is not available, and the user tries to navigate to the next page ConnectionLost
Component would be there.
But if there is no network and user do not take any action means not navigating to the second page. then there should not be a connection-lost page. The user should stay on the current page.
For that, I have implemented canActivate guard as the following code:
@Injectable({
providedIn: 'root'
})
export class NetworkGuard implements CanActivate {
constructor(private router: Router, private network: NetworkService) {
}
canActivate(next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (window.navigator.onLine) {
return true;
} else {
if (!this.isConnectionLostComponent()) {
this.router.navigate(['/connection-lost'], {skipLocationChange: true});
}
return false;
}
}
private isConnectionLostComponent() {
// check whether connection lost component is added on not
return this.network.isActive;
}
}
It's working fine except for one condition.
That is if I click back or forward from the browser, its update URL connection-lost
to the address bar
How could I solve this problem? Can see the sample Here
steps to produce the issue:
- Click banner(Button) -> URL change to '/banner'
- Click brand(Button) -> URL change to '/brand'
- Disconnect network on that brand page
- Click back from browser-> ConnectionLostComponent and url is '/brand', that's okay
- Click back again -> ConnectionLostComponent but url is also changed to '/connection-lost'. that's what I'm facing the problem.
I just don't want to update the URL with '/connection-lost', for that I added skipLocationChange: true
option to router.navigate
method in the NetworkGuard
, But still it's not working.