问题
I create auth app with routing in angular 2 with typescript. And now my task is disabled back button in browser from form localhost/form1
to localhost/login
; how implement this?
回答1:
You can't really block the back button since it's a browser behavior. What you can do instead is to create a guard to handle every request, and if the request is done to load /login and the user is already loggued, simply redirect to the previous page.
回答2:
I solved this in my angular cordova app to prevent app from exiting as following. Contrary to most comments I've found I had to use the "document" object instead of the "window" object to capture the backbutton event
// Prevent from exiting app by hook into document backbutton
@HostListener('document:backbutton', ['$event'])
onPopState(event) {
alert('Start page');
}
Usage in a component
import { Component, HostListener } from '@angular/core';
export class myComponent {
constructor() {}
// Prevent from exiting app by hook into document backbutton
@HostListener('document:backbutton', ['$event'])
onPopState(event) {
alert('Start page');
}
}
回答3:
step 1: Import Locatoion from angular commmon
import {Location} from "@angular/common";
step 2: Initialise in constructor
private commonService: CommonService
step 3: Add function in ngOnInit of the respective coponent,
this.location.subscribe(currentLocation => {
if (currentLocation.url === '*/basic-info*') {
window.onpopstate = function (event) {
history.go(1);
}
}
});
Note: Here /basic-info will be replaced by your path.
If first time it is not working, try adding outside subscribe,
let currentUrl = window.location.href;
let tmpVar = currentUrl.includes('/basic-info');
if (currentUrl.includes('/basic-info')) {
window.onpopstate = function (event) {
history.go(1);
}
}
来源:https://stackoverflow.com/questions/41035672/disable-back-page-button-in-browser