角度:按下浏览器后退按钮时关闭模态并取消导航

时间:2019-10-18 14:50:38

标签: angular angular-routing angular-router

当我用以下代码按下浏览器后退按钮时,我试图关闭全窗口模式:

class MyModalComponent {
  constructor(private _location: LocationStrategy) { }

  public ngOnInit(): void {
    this._location.pushState(this.url, this.title, this.url, '');
  }

  @HostListener('window:popstate', ['$event'])
  public onPopState(event: PopStateEvent) {
      this.modal.dismiss();
      event.preventDefault();
      event.stopPropagation();
      event.cancelBubble = true;
  }
}

按下后退按钮时,将调用onPopState并取消使用模式,但是Angular Router也会检测到URL更改并开始导航到先前的状态。打开模式后,有什么方法可以取消导航或阻止Angular Router监听URL更改吗?

1 个答案:

答案 0 :(得分:0)

一个肮脏的解决方案可能是将onSameUrlNavigation路由器属性设置为'ignore'并将当前URL推入导航历史记录,以防止后退按钮调用路由器导航:

class MyModalComponent {
  private _prevOnSameUrlNavigation; 

  constructor(private _location: LocationStrategy, private _router: Router) {

  }

  public ngOnInit(): void {
    this._prevOnSameUrlNavigation = this._router.onSameUrlNavigation;
    this._router.onSameUrlNavigation = 'ignore';
    this._location.pushState("Modal state", "Modal title", this._router.url, '');
  }

  @HostListener('window:popstate', ['$event'])
  public onPopState(event: PopStateEvent) {
      this.modal.dismiss();
      event.preventDefault();
      event.stopPropagation();
      event.cancelBubble = true;
  }

  public ngOnDestroy() {
      this._router.onSameUrlNavigation = this._prevOnSameUrlNavigation;
  }
}