Angular 4 路由器 : prevent direct browser navigation

标签 angular angular-routing angular4-router

如何说服 Angular 4 路由器在我的应用中禁用直接浏览器导航?

我查看了路由器 Hook CanActivateCanDeactivate 并实现了它们,但是在使用直接浏览器导航时 CanDeactivate 根本不会触发。

我可以使用 CanActivate 来阻止 url,但只能在应用程序重新启动后进行,这需要时间并且浏览器窗口中会出现不需要的更改。

我希望能够在应用重启之前捕捉到直接的浏览器导航。

如果这有帮助: 我想完全禁止直接浏览器导航,因此我不需要允许某些 url 并禁用其他 url 的解决方案。

这是我的路由器定义:

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard', component: DashboardComponent, canActivate: [RouteGuardService] },
  { path: 'users', component: UsersMainComponent, canActivate: [RouteGuardService] },
  { path: 'vendors', component: VendorMainComponent, canActivate: [RouteGuardService] },
  { path: 'invoices', component: InvoicesMainComponent, canActivate: [RouteGuardService] },
  { path: 'offers' , component: EsdMainComponent, canActivate: [RouteGuardService] },
  { path: 'settings' , component: SettingsMainComponent, canActivate: [RouteGuardService] },
  // Callback MUST not be route guard protected.
  { path: 'callback' , component: CallbackComponent },
  { path: 'createvendor' , component: CreateVendorsComponent, canActivate: [RouteGuardService] },
  { path: 'customerdashboard' , component: CustomerDashboardComponent, canActivate: [RouteGuardService] },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [RouteGuardService]
})
export class AppRoutingModule { }

最佳答案

以下解决方案不是基于 Angular 的解决方案。正如 Maximus 在他的回答中解释的那样,这是一个浏览器问题,因此解决方案必须基于浏览器。

此解决方案源自本网站 ( see here ) 上的一个答案,我使用以下三种方法编写了一个小的 (typescript) 服务:

  private preventNavigation(): void {
    const location = window.document.location;
    const originalHashValue = location.hash;

    window.setTimeout(() => {
      location.hash = 'preventNavigation' + (9999 * Math.random());
      location.hash = originalHashValue;
    }, 0);
  }

  public disableBrowserNavigation(): void {
    window.addEventListener('beforeunload', this.preventNavigation, false);
    window.addEventListener('unload', this.preventNavigation, false);
  }

  public enableBrowserNavigation(): void {
    window.removeEventListener('beforeunload', this.preventNavigation);
    window.removeEventListener('unload', this.preventNavigation);
  }

这很好用,但我仍然对其他解决方案持开放态度。

关于 Angular 4 路由器 : prevent direct browser navigation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45427632/

相关文章:

javascript - 为什么启用 html5mode 后 AngularJS 路由会被破坏?

angular - 相当于组件功能的路由守卫

html - 当内部有 2 个或更多组件时,为什么我的 Angular 应用程序无法正确设置背景?

javascript - 无法以 Angular 2 绑定(bind)数据

javascript - 如何在断开连接或浏览器关闭后注销用户?

子模块的 Angular 合并路线

javascript - 无法在 AngularJS 中实例化模块

javascript - 从应用程序中直接输入的网址读取路由参数

angular - 以 Angular 4 的路线更改自动保存表单/模型内容

typescript - 从 Angular 2 typescript 中的复选框获取值(value)