Thursday, 21 February 2019

How to implement canActivate guard for the network connection in Angular2+?

I have implemented canActivate guard like below 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?

here is the sample: https://stackblitz.com/edit/angular-h8dhxw

steps to produce the issue
1. Click banner(Button) -> URL change to '/banner'
2. Click brand(Button) -> URL change to '/brand'
3. Disconnect network on that brand page
4. Click back from browser-> ConnectionLostComponent and url is '/brand', that's okay
5. 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.



from How to implement canActivate guard for the network connection in Angular2+?

No comments:

Post a Comment