I have one login page as part of my application . I want to disable my back button after logout successfully so that the user can not go back.
// Disable browser back button code start. setTimeout("preventBack()", 0); window. onunload = function () { null };
To prevent browse back navigation we make use of History. pushState() web api. As soon as the user lands on the component where we want to disable back navigation, we set history. pushState(null, '') .
Run your application by typing the ng serve or ng build commands in your command line or terminal, and see the results: The browser back button will be disabled for whole the application.
You can add a guard to watch and decide if user can access the page or not rather than disabling the browser's events. CanActivate
is the saviour
CanActivate (Interface)
Interface that a class can implement to be a guard deciding if a route can be activated. If all guards return true, navigation will continue. If any guard returns false, navigation will be cancelled. From official documentation of Angular
Here I am adding some code that I am currently using. Hope it helps to understand how to implement one.
import { CanActivate, ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router';
import { IdentityService } from './identity.service';
@Injectable()
export class LoginGuard implements CanActivate {
constructor(private identityService: IdentityService, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.identityService.isLoggedIn()) { // determine if the uder is logged in from this method.
return true;
}
this.router.navigate(['/login']);
return false;
}
}
add this LoginGuard class into provider in you app.module.ts
providers: [{ provide: LoginGuard, useClass: LoginGuard }]
then add canActive
in the route to guard it.
{
path: 'dashboard',
component: DashboadComponent,
canActivate: [LoginGuard]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With