CanDeactivate 更改 window 历史记录

CanDeactivate changing the window history

我遇到了 canDeactivate() 的一些问题,每当它 returns false 它正在改变 window 历史,当它变成 true 时,如果我点击后退按钮。我正在导航到其他 URL 或离开应用本身。

请帮帮我

Here 是问题,但仍未解决。

作为解决方法,您可以手动将活动 url 放回历史记录:

export class CanDeactivateGuard implements CanDeactivate<any> {
    constructor(
        private readonly location: Location,
        private readonly router: Router
    ) {}

    canDeactivate(component: any, currentRoute: ActivatedRouteSnapshot): boolean {
        if (myCondition) {
            const currentUrlTree = this.router.createUrlTree([], currentRoute);
            const currentUrl = currentUrlTree.toString();
            this.location.go(currentUrl);
            return false;
        } else {
            return true;
        }
    }
}

Angular 路由问题仍然存在,以下是对我有用的方法。

技巧是使用this.router.navigate([currentUrl], { skipLocationChange: true });

完整代码:

export class CanDeactivateGuard implements CanDeactivate<any> {

  constructor(
    private location: Location,
    private router: Router
  ) { }

  canDeactivate(component: any,
    currentRoute: ActivatedRouteSnapshot, 
    currentState: RouterStateSnapshot): boolean {

    if(canDeactivateCondition) {
      return true;
    } else {
      const currentUrl = currentState.url;
      if (this.location.isCurrentPathEqualTo(currentUrl)) {
        // https://github.com/angular/angular/issues/13586
        this.router.navigate([currentUrl], { skipLocationChange: true });
      } else {
        // A browser button has been clicked or location.back()/forward() invoked. Restore browser history
        history.pushState(null, null, location.href);
      }

      return false;
    }
  }
}

这是 Angular 中的已知错误:https://github.com/angular/angular/issues/13586

提出了很多解决方法,但所有这些似乎都会破坏其他部分。

现在似乎已在 Angular 12.1.2 中修复:https://github.com/angular/angular/issues/13586#issuecomment-881627456