如何处理确认框的取消事件?
我的目标是在点击浏览器后退按钮时向用户显示一个确认框,如果用户按下确定按钮,则必须将其重定向到后面(/users),这很好地工作,但如果用户按下取消,则不必返回到上一页,但在两种情况下都返回到了上一页。
this.router.navigate(['user-details']) 根本不起作用,而
window.history.pushState({}, "user-details", "/user-details");
只是更改了URL,而不是页面。请注意保留HTML标记。export class UserDetailsComponent implements OnInit, OnDestroy {
r: boolean;
confirmtxt;
canceltxt;
paymentList = [];
constructor(
private router: Router,
private dataService: DataService,
private location: Location
) {
this.getPaymentSummaryData();
}
ngOnInit() {
this.location.subscribe(x => {
console.log(this.location);
console.log(x);
if (x.type === "popstate") {
console.log("data is " + this.paymentList.length);
const str = String(this.paymentList.length);
console.log(str);
this.r = confirm(
"Are you sure?" +
" " +
str +
" " +
"applications are in the queue, awaiting decision."
);
console.log(this.r);
if (this.r === true) {
// txt = "You pressed OK!";
this.confirmtxt = "ok";
} else {
this.r = false;
// history.forward();
}
}
});
console.log(this.r);
}
ngOnDestroy() {
console.log('in destroy' + this.r);
if (this.r === false) {
this.router.navigate(['user-details']);
window.history.pushState({}, "user-details", "/user-details");
this.router.navigate(["user-details"]);
window.location.reload();
}
// this.location.unsubscribe();
}
}
window.history
?这就是路由器的作用。 - Lazar Ljubenovićwindow.history
只是改变 URL,因为这正是你调用的函数应该做的。你从错误的角度来解决问题。不要试图通过历史 API 来修复它,而是找出路由器为什么不能正常工作。 - Lazar Ljubenović