CanDeactivate更改窗口历史记录

时间:2017-09-27 12:39:39

标签: angular2-routing

我遇到canDeactivate()的一些问题,只要它返回false,它就会改变窗口历史记录,就像它变为真,如果我点击后退按钮。我正在导航到其他URL或应用程序本身。

请帮帮我

2 个答案:

答案 0 :(得分:2)

Here是问题所在,但仍然没有解决。

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

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

答案 1 :(得分:0)

该问题仍然存在于 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;
    }
  }
}
相关问题