首页 > 解决方案 > Angular 5 router.navigate 让我远离 Angular 应用程序

问题描述

在我的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/coolAngular 应用程序时,会加载并推送一个历史状态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 的路由器上没有明确的选项或功能来强制它执行“内部重定向”而不导致整个页面重新加载 - 或者我只是错过了一些东西?

标签: angularangular2-routing

解决方案


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

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

推荐阅读