hho*_*tij 7 angular-routing angular angular4-router
如何说服Angular 4路由器在我的应用程序中禁用直接浏览器导航?
我已经查看了路由器钩子CanActivate并CanDeactivate实现了它们,但CanDeactivate在使用直接浏览器导航时根本不会触发.
我可以CanActivate用来阻止网址,但只有在应用程序重新启动后,这需要时间和浏览器窗口中的不需要的更改.
我希望能够在应用重新启动之前捕获直接浏览器导航.
如果这有帮助:我想完全禁止直接浏览器导航,所以我不需要允许某些网址并禁用其他网址的解决方案.
这是我的路由器定义:
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 { }
Run Code Online (Sandbox Code Playgroud)
以下解决方案不是基于Angular的解决方案.正如Maximus在他的回答中解释的那样,这是一个浏览器问题,因此解决方案必须基于浏览器.
这个解决方案来源于这个网站上的答案(见这里)我用以下三种方法编写了一些(打字稿)服务:
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);
}
Run Code Online (Sandbox Code Playgroud)
这很好但我仍然对其他解决方案持开放态度.
如何说服 Angular 4 路由器在我的应用程序中禁用直接浏览器导航?
Angular 无法做到这一点,因为那不是 Angular 控制的东西。当您转到地址栏并输入地址,然后按 Enter 键时,浏览器会加载一个新页面。它可以是 Angular 应用程序,也可以是任何其他应用程序。这是浏览器的功能。当您单击时, Angular 仅在应用程序内部控制导航routerLink。
您可以尝试使用onbeforeunload但它有其局限性。
| 归档时间: |
|
| 查看次数: |
6795 次 |
| 最近记录: |