Angular2 [routerLink]工作,this.router.navigate似乎崩溃了应用程序

时间:2017-03-11 18:54:36

标签: angular routes routerlink

我在使用像这样的按钮的Angular2应用程序中的路由时遇到问题:

<button [routerLink]="['/home/maincomponent']>Click</button>

但是在函数中使用相同的路径失败 - 页面似乎加载了一瞬间,然后应用程序完全刷新并让我回到主/根页面,但控制台上没有错误。

goToComponent() {
    this.router.navigate(['/home/maincomponent']); 
}

此外,只需在浏览器中输入路径导航到路径就可以正常加载组件而不会出现任何错误或重定向。

http://localhost:4000/#/home/component

路由器配置:

const routes: Routes = [
  {
    path: 'home', 
    component: HomeComponent,
    children: [{ 
      path: '', 
          redirectTo: 'dashboard',
          pathMatch: 'full'
        },
      { 
      path: 'dashboard', 
          component: DashboardComponent
        },
      {
      path: 'search', 
          component: SearchComponent
        },
      {
      path: 'maincomponent', 
          component: MainComponent
        },
      {
      path: '**', 
          component: DashboardComponent
      }]
  }
];

@NgModule配置:

RouterModule.forRoot(routes,
{
  useHash: true,
  preloadingStrategy: PreloadAllModules
}),

1 个答案:

答案 0 :(得分:1)

我找错了地方找问题。我将函数调用(单击)绑定到

<a href="" (click)="goToComponent">LINK</a> 

元素,失败。

切换到

<span (click)="goToComponent">LINK</span> 

元素解决了这个问题。

相关问题