Angular 中的路由 2 将数据从路由/HTML 传递到组件

Routing in Angular 2 passing data from route / HTML to component

嗨,我是 Angular 的新手 2. 我必须为 5 个选项卡创建路由。我有这 5 个选项卡的 5 个代码,我需要发送这些代码以从后端检索数据。我已经有这些代码的服务。当我单击选项卡时,我需要通过服务发送该代码并检索和显示数据。我正在通过 Angular 2 TypeScript 完成所有这些工作。我不明白如何将这段代码从路由发送到 Angular 2 服务。(同时我还需要将这段代码发送到后端网络服务)我的网络服务和 Angular 2 服务是 运行 并在我通过一些试用输入代码时提供数据输出。我需要将代码作为数字传递如下。

HTML
<a id="item1" [routerLink]="['/item1', 1]"> item1 </a>
<a id="item2" [routerLink]="['/item2', 2]"> item2 </a>
<a id="item3" [routerLink]="['/item3', 3]"> item3 </a>
<a id="item4" [routerLink]="['/item4', 4]"> item4 </a>
<a id="item5" [routerLink]="['/item5', 5]"> item5 </a>

Routes
{ path: 'items/:1', component: ItemsComponent },
{ path: 'items/:2', component: ItemsComponent },
{ path: 'items/:3', component: ItemsComponent },
{ path: 'items/:4', component: ItemsComponent },
{ path: 'items/:5', component: ItemsComponent },

Component.ts

你可以在ngOnInit中从route中获取id的值,然后使用这个id进行服务调用如下:

ngOnInit() {
  let id = this.route.snapshot.paramMap.get('id');
  this.data = this.service.getData(id);
}

确保您已准备好所有导入:

import { ActivatedRoute, ParamMap } from '@angular/router';

此外,在使用':'时,路由用占位符描述如下:

{ path: 'item/:id', component: ItemsComponent }

或者如果你必须手动描述每条路线那么不要使用:并写成如下。

{ path: 'item/1', component: ItemsComponent }
// and so on for 2,3,4,5
// NOT RECOMMENDED THOUGH | THIS IS BAD PRACTICE