【问题标题】:CanDeactivate Not Firing in iFrameCanDeactivate 在 iF​​rame 中不触发
【发布时间】:2021-04-07 20:06:41
【问题描述】:

我有一个应用程序,它有一个 iframe 到一个单独的 Angular 应用程序中。 iframe 的 src 是一个组件。长话短说,Angular 应用程序必须重定向到主页,然后返回到 src 中的组件。如果我在光标位于 iframe 中时使用鼠标上的后退按钮,Angular 应用程序会返回到主页(因为它从那里重定向)。所以,为了防止这种情况,我把这个守卫放在组件的路由上。

@Injectable({
  providedIn: 'root',
})
export class CannotDeactivateGuard implements CanDeactivate<unknown> {
  canDeactivate(
    component: unknown,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState?: RouterStateSnapshot
  ):
    | Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree>
    | boolean
    | UrlTree {
    // Always returns false as we do not want the user to navigate away.
    // Example use is if a component is used in an iframe. We do not want the user to be able to navigate within the iframe.
    console.log('RETURN FALSE FROM CANNOT DEACTIVATEGUARD');
    return false;
  }
}

控制台未记录消息,应用程序仍在返回主页。

更新

我注意到,即使直接在其自己的页面上(不是在 iframe 中)点击组件时,当单击后退按钮时,CannotDeactivateGuard 也不会触发。

【问题讨论】:

    标签: angular iframe angular-router-guards candeactivate


    【解决方案1】:

    我发现的一种解决方法是在组件的 ngOnInit() 中调用此代码。

    constructor(protected locationStrategy: LocationStrategy) {}
    
    ngOnInit(): void {
      history.pushState(null, null, location.href);
      this.locationStrategy.onPopState(() => {
        history.pushState(null, null, location.href);
      });
    }
    

    这不是很好。我希望 Angular 的 CanDeactivate 在实施时能解决这个问题。越用越失望。

    【讨论】:

      猜你喜欢
      • 2012-04-15
      • 1970-01-01
      • 2019-05-08
      • 2012-01-31
      • 1970-01-01
      • 1970-01-01
      • 2015-10-03
      • 2019-05-12
      • 2020-05-15
      相关资源
      最近更新 更多