angular - Angular 5 router.navigate 让我远离 Angular 应用程序
问题描述
- 我有一个升级到 Angular 5 的 Angular 4 项目,我注意到路由的行为似乎有所不同,尽管它可能一直是这样的。
- 我的
index.html
文件<base href="/cool/" />
在<head>
元素中。 - 我的网络服务器为 下
index.html
的所有请求提供内容/cool
,例如:GET /cool
GET /cool/
GET /cool/auth
GET /cool/auth/
GET /cool/somethingElse/
- ...但不是为了
GET /
在我的app.routing.ts
文件中,我设置了这些路线:
const appRoutes: Routes = [
{ path: 'home' , component: HomeComponent },
{ path: 'misc' , component: MiscComponent },
{ path: 'help' , component: HelpComponent },
{ path: 'auth' , component: AuthComponent },
{ path: '' , redirectTo: '/home', pathMatch: 'full' },
{ path: '**' , component: NotFoundComponent }
];
因此,当用户访问http://localhost/cool
Angular 应用程序时,会加载并推送一个历史状态http://localhost/cool/home
(因此地址栏会发生变化,但浏览器不会对新位置进行整页重新加载)。到目前为止,一切都很好。
我的页面中有一个注销按钮(在 HTML 中由 控制AppComponent
),单击该按钮时会执行以下操作:
class AppComponent {
logOutClicked( event: Event): void {
this.clientTokenService.clearSavedToken();
this.router.navigate( ['auth'] );
}
}
...但是当这种情况发生时,浏览器会刷新整个页面http://localhost
或者http://localhost/auth
(我忘记了是什么导致它这样做,我想是我这样做的时候router.navigate( ['/auth'] )
——我现在无法访问 Angular 应用程序来检查) .
我很惊讶 Angular 的路由器上没有明确的选项或功能来强制它执行“内部重定向”而不导致整个页面重新加载 - 或者我只是错过了一些东西?
解决方案
使用路由器链接而不是 href。这将在不重新加载的情况下路由
<a routerLinkActive="active" [routerLink]="['/cool']">Cool Page</a>
推荐阅读
- php - 如何跟踪倒数计时器并存储时间以备后用
- javascript - 如何使用 jQuery 在表格行单击时过滤表格中的数据?
- python - 无法安装深度动画师
- sql - 如何从包含 postgresql 的所有列的表中查找 Min 和 Max 行
- php - 文本框未填充来自 URL 的数据?
- julia - Julia 惯用的捕捉异常的方式,除了中断?
- c# - 上传 30 MB 以上 ASP.NET Core 3.1 时出现 504 错误
- powerbi - Power BI 视觉对象中的时间框架(又名 Sprint)字段出现故障
- django - 有没有办法用组件构建页面
- python - 使用 for 循环在列表中搜索值并打印搜索结果