【发布时间】:2018-01-04 11:47:12
【问题描述】:
如何处理确认框的取消事件?
我的目标是在单击浏览器后退按钮时向用户显示一个确认框,如果用户按下确定按钮,那么我必须将其向后重定向(/用户),这工作正常,但如果用户按下取消,那么我没有转到上一页,但在这两种情况下,它都会转到上一页。
this.router.navigate(['user-details]) 根本不工作,而 window.history.pushState({}, "user-details", "/user-details"); 只是更改 url,而不是页面。
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?这就是路由器的用途。 -
我尝试了它作为替代方案,因为 this.router.navigate() 没有像我在问题中提到的那样工作。
-
window.history只是更改 URL,因为这正是您调用的函数应该做的。你从错误的角度处理问题。与其尝试使用历史 API 修复它,不如找出路由器无法正常工作的原因。
标签: javascript angular