如何说服 Angular 4 路由器在我的应用中禁用直接浏览器导航?
我查看了路由器 Hook CanActivate
和 CanDeactivate
并实现了它们,但是在使用直接浏览器导航时 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/