角度2路线导航,名称而不是路径

时间:2018-02-10 04:18:44

标签: angular routing routes angular2-routing

我正在使用angular cli版本 - 1.6.0 我使用过的这些路线。

App.module.ts

{{#each model as |client|}}
<tr>
<td>{{client.id}}</td>
<td>{{#link-to "clients.client.requests" client}}

我使用像这样的导航

App.component.ts

const routes: Routes = [
  { path: '', component: AppComponent },
  { path: 'tutorial', component: TutorialComponent },
];

App.component.html

this.router.navigate(['/tutorial']);

这些都很好,但我希望使用名称而不是路径或网址进行路线导航。我不想在所有组件中包含我的导航网址。我只需要为我的路线设置名称,并希望在所有组件中使用该名称进行路线导航。

这样可以使用吗? 谁能帮忙解决这个问题? 提前谢谢。

1 个答案:

答案 0 :(得分:2)

据我了解,您想使用名称而不是直接路径。你可以通过制作Route.ts文件来做到这一点。

例如 -

// route.ts file
export class Route {
public static TUTORIAL = 'tutorial';
}

并在任何您想使用它的地方使用该文件。

this.router.navigate(['/' + Route.TUTORIAL]);

<div class="nav-menu-blocks">
    <a routerLinkActive="w--current" [routerLink]="tutorialUrl" class="nav-link w-nav-link">About</a>
  </div>

// TS file
get tutorialUrl() {
return ['/' + Route.TUTORIAL];
}

这种方法的好处是,将来如果你想改变这条路,你不需要在任何地方改变它。只需要在Route文件中更改它。

希望这有帮助。