【问题标题】:Angular 5 router.navigate takes me away from the Angular applicationAngular 5 router.navigate 让我远离 Angular 应用程序
【发布时间】:2018-11-07 03:01:54
【问题描述】:
  • 我有一个 Angular 4 项目,我升级到 Angular 5,我注意到路由的行为似乎有所不同,尽管它可能一直都是这样。
  • 我的index.html 文件在<head> 元素中有<base href="/cool/" />
  • 我的网络服务器为/cool 下的所有请求提供index.html 的内容,例如:
    • 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://localhosthttp://localhost/auth 进行整页刷新(我忘记是什么原因导致它这样做了,我想是在我这样做的时候router.navigate( ['/auth'] ) - 我没有'现在无法访问 Angular 应用程序进行检查)。

我很惊讶 Angular 的路由器上没有明确的选项或功能来强制它执行“内部重定向”而不导致整个页面重新加载 - 或者我只是错过了一些东西?

【问题讨论】:

  • AFAIK angular 的路由器不会导致整页重新加载。也许您在某处有一些代码可以设置 window.location 属性?
  • 另外,是否有控制台错误?
  • @YoukouleleY 没有错误,只是网络选项卡(和一个 XHR 断点)显示了对站点根目录的 XHR 请求,它以某种方式触发了整个页面的重新加载,这很奇怪。
  • 您是否尝试使用此行启用路由器跟踪:RouterModule.forRoot(routes, {enableTracing: true})
  • 我已经看到当你有一个带有 onClick 处理程序的按钮时会发生这种情况。如果您的按钮在表单中,它可能是一个提交按钮,而您却没有意识到它正在尝试提交表单?

标签: angular angular2-routing


【解决方案1】:

使用路由器链接而不是 href。这将在不重新加载的情况下路由

<a routerLinkActive="active" [routerLink]="['/cool']">Cool Page</a>

【讨论】:

    【解决方案2】:

    将“a”标签更改为 div 或 span。 当你有一个没有 href 属性和 routerLink 属性的“a”标签时,它仍然是一个链接,我认为它的默认值是“/”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-17
      • 1970-01-01
      • 2016-11-03
      • 1970-01-01
      • 2018-08-15
      • 2019-03-29
      • 2015-11-01
      • 2021-09-05
      相关资源
      最近更新 更多