Prevent reverse navigation in angular app (mobile)

I need to prevent the user from navigating backwards in some parts of the application that I create. So far I am using this method:

ngOnInit() { 

 history.pushState(null, null, location.href);   
 window.onpopstate = function(event) {
   history.go(1);
 };
}

ngOnDestroy() {
 window.onpopstate = function(event) {
   history.go();
 };
}

This works great except iOS Chrome and Safari. I also tried:

history.replaceState(null, document.title, location.pathname);

in ngOnInit with luck. Can someone talk about how browsers on these mobile devices use history and / or pop up differently than in versions of windows / macOS browsers?

+4
source share
1 answer

Instead of trying to implement various browser solutions, I would think of Angular CanDeactivateguard .

Suppose you have a service (call it NavigatorService) that always saves the previous route:

@Injectable()
export class NavigatorService{
  private previousRoute:string = null;
  private currentRoute:string = null;
  /** Listen to and log new route paths */
  constructor(private router:Router){
    router.events.filter(e => e instanceof NavigationEnd).subscribe(
      e => {
        this.previousRoute = this.currentRoute;
        this.currentRoute = e['url'];
      }
    )
  }
  /** Checks whether the next route corresponds to the previous route  */
  isGoingBack(nextState:RouterStateSnapshot){                   
      return nextState.url === this.previousRoute;
  }
}

CanDeactivateGuard, , , :

@Injectable()
export class BackwardGuard implements CanDeactivate<any> {
  // Inject the service needed
  constructor(navigatorService:NavigatorService){}

  // Angular 4 provides these arguments to any CanDeactivate guard
  // see https://angular.io/api/router/CanDeactivate#interface-overview
  canDeactivate(component:any, currentRoute:ActivatedRouteSnapshot, 
             currentState:RouterStateSnapshot, nextState:RouterStateSnapshot){                   
      // Allow navigation only if the user is not going back
      return !this.navigatorService.isGoingBack(nextState);
  }
}

, , :

appRoutes:Routes = [
  {
    path: 'some-path',
    component: ProtectedComponent,
    canDeactivate: [BackwardGuard]
  }
];

, , , , . NavigatorService (: AppModule) BackwardGuard (: AppRoutingModule)

+2

Source: https://habr.com/ru/post/1689075/


All Articles