【问题标题】:How can I handle cancel event of confirm box?如何处理确认框的取消事件?
【发布时间】: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


【解决方案1】:

我不知道为什么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();
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    相关资源
    最近更新 更多