如何在 Angular2 CLI 中声明默认路由?

How to declare default route in Angular2 CLI?

我使用 angular CLI 创建了一个小项目,但我不知道如何在 CLI 中声明默认路由。我对 parent 组件使用“/”,它可以工作,但如果我对 child 组件使用“/”,它就不起作用。

我的parent.component.ts是:

@Routes([
  { path: '/', component: LoginComponent },
])   

parent.component.html 是:

<a [routerLink]="['/Login']"></a>
<router-outlet></router-outlet>

child.component.ts 是:

@Routes([
    { path: '/', component: DashboardComponent},
])

child.component.html 是:

<li class="treeview">
    <a [routerLink]="['']">Dashboard</a>
</li>
<router-outlet></router-outlet>

此方法适用于 parent 和 child,但我想要一条具有另一条路径的路线,例如默认为“/仪表板”。 有什么方法可以在 child 组件中定义默认路由。

将此选项放入您的路由配置中

{ ...,  terminal: true}

我想你必须试试这个:-

export const HomeRoutes: RouterConfig = [
    { path: '', redirectTo: '/home', terminal: true},
    { path: 'home', component: HomeComponent, terminal: true }
];

PS:- 未测试 Credit to this answer

更新

您也可以尝试像这样定义两次路线:-

{ path: '/', component: HomeComponent}
{ path: 'home', component: HomeComponent}

这样一来,同一组件就有了默认路由器和命名路由器。

希望能帮到你。