Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to disable the back button after logout in angular 7

Tags:

angular

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.

like image 823
Saroj Kumar Sahoo Avatar asked Jan 31 '19 12:01

Saroj Kumar Sahoo


People also ask

How to disable browser back button after logout in angular?

// Disable browser back button code start. setTimeout("preventBack()", 0); window. onunload = function () { null };

How to prevent back button after login in angular?

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, '') .

Can we disable browser Back button in angular?

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.


1 Answers

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]
}
like image 172
Sadid Khan Avatar answered Nov 02 '22 23:11

Sadid Khan