Naresh
Naresh

Reputation: 61

Angular - Only allow routing if routed using router.navigate() method

My requirement is to prevent the user navigation if the user changes browser URL manually from address bar. Routing should only be done through angular app(router.navigate()).

I know that we can implement route guard using canActive property.

canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

}

But I don't know which properties of ActivatedRouteSnapshot or RouterStateSnapshot I can use to identify that the user is navigating inside the application using manual url change. Can you please help.

Upvotes: 3

Views: 1362

Answers (2)

Xabier
Xabier

Reputation: 11

I have recently faced this problem and I think I have solved it or at least it works for me.

canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

  const nav = this.router.getCurrentNavigation();

  if (nav.id === 1 || nav.previousNavigation !== null) {
    this.router.navigate(['/somewhere']);
  } else {
    return true;
  }
}

The property 'id' of navigation object indicates the number within the user's browsing history within the application. So id === 1 would indicate that the user has entered by browser address first time and not by redirection via router.navigate()

If the user was already browsing the application, we have to check that there is a previous registered navigation and to be able to control from where they are browsing.

Upvotes: 1

Orodan
Orodan

Reputation: 1047

I don't think this is possible with the ActivatedRouteSnapshot or with any other classes.

I would add this is a strange behavior for your application, because it also means you don't want your user to be able to refresh your page. If you fear that by manualy navigating to your component, you don't have enough data for it to work properly, you can use a guard as you mentionned.

Hope that helps

Upvotes: 1

Related Questions