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

时间:2018-01-04 11:47:12

标签: javascript angular

如何处理确认框的取消事件? 我的目标是在点击浏览器后退按钮时向用户显示一个确认框,如果用户按下确定按钮,那么我必须向后重定向(/用户),这是正常工作,但如果用户按下取消,那么我没有转到上一页,但在这两种情况下,都会转到上一页。 this.router.navigate(['user-details])根本不起作用,而window.history.pushState({}, "user-details", "/user-details");只是更改网址,而不是网页。

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();
  }
}

1 个答案:

答案 0 :(得分: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();
  }