如何处理确认框的取消事件?

3
如何处理确认框的取消事件? 我的目标是在点击浏览器后退按钮时向用户显示一个确认框,如果用户按下确定按钮,则必须将其重定向到后面(/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ć
我尝试了这个替代方案,因为像我在问题中提到的那样,this.router.navigate() 没有起作用。 - Humble Dolt
1
window.history 只是改变 URL,因为这正是你调用的函数应该做的。你从错误的角度来解决问题。不要试图通过历史 API 来修复它,而是找出路由器为什么不能正常工作。 - Lazar Ljubenović
1个回答

0

我不知道为什么this.router.navigate(['url'])无法工作。所以我改成了this.router.navigateByUrl('/url')的方法。另外,布尔值在开始时将是undefined,因此也需要检查它。 这两个更改都在ngOnDestroy()中对我有用。

ngOnDestroy() {
    console.log('in destroy' + this.r);
    if (this.r === false) {
     this.router.navigateByUrl('/user-details');

    } else if ( !this.r )  {
           this.router.navigateByUrl("/user-details");
    }
    // this.location.unsubscribe();
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接