Instead of trying to implement various browser solutions, I would think of Angular CanDeactivate
guard .
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;
constructor(private router:Router){
router.events.filter(e => e instanceof NavigationEnd).subscribe(
e => {
this.previousRoute = this.currentRoute;
this.currentRoute = e['url'];
}
)
}
isGoingBack(nextState:RouterStateSnapshot){
return nextState.url === this.previousRoute;
}
}
CanDeactivateGuard, , , :
@Injectable()
export class BackwardGuard implements CanDeactivate<any> {
constructor(navigatorService:NavigatorService){}
canDeactivate(component:any, currentRoute:ActivatedRouteSnapshot,
currentState:RouterStateSnapshot, nextState:RouterStateSnapshot){
return !this.navigatorService.isGoingBack(nextState);
}
}
, , :
appRoutes:Routes = [
{
path: 'some-path',
component: ProtectedComponent,
canDeactivate: [BackwardGuard]
}
];
, , , , . NavigatorService
(: AppModule
) BackwardGuard
(: AppRoutingModule
)