Issue
Hi I am new to Angular 2. I have to create routes for 5 tabs. I have 5 codes for these 5 tabs and I need to send these codes to retrieve data from the backend. I already have a service for these codes. When I click on a tab I need to send that code through the service and retrieve and display the data. I am doing all this through Angular 2 TypeScript. I am not understanding how I can send this code from the route to the Angular 2 service.(at the same time I need to send this very code to the backend webservice as well) My webservice and Angular 2 service are running and giving data output when I pass some trial input codes. I need to pass the codes as numbers as below.
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
Solution
You can get the value of id from route inside ngOnInit, then use this id to make a service call as follows:
ngOnInit() {
let id = this.route.snapshot.paramMap.get('id');
this.data = this.service.getData(id);
}
Make sure you have all imports in place:
import { ActivatedRoute, ParamMap } from '@angular/router';
Furthermore, routes are described with placeholder when using ‘:
‘ as follows:
{ path: 'item/:id', component: ItemsComponent }
Or if you have to describe each route manually then don’t use :
and write as follows.
{ path: 'item/1', component: ItemsComponent }
// and so on for 2,3,4,5
// NOT RECOMMENDED THOUGH | THIS IS BAD PRACTICE
Answered By – Peter
Answer Checked By – Mary Flores (AngularFixing Volunteer)