Reading route parameter values
To read the route parameter value use Angular ActivatedRoute service.
- There are 2 ways to read the route parameter value.
- We can either use the snapshot approach or observable approach.
- If you expect users to navigate from employee to employee directly, without navigating to another component first, then you need to use the observable approach. We will discuss the observable approach later.
Introduce getEmployee() method in employee.service.ts file
getEmployee(id: number): Employee {
return this.listEmployees.find(e => e.id === id);
}
employee-details.component.html
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">{{employee.name}}</h3>
</div>
<div class="panel-body">
<div class="col-xs-10">
<div class="row vertical-align">
<div class="col-xs-4">
<img class="imageClass" [src]="employee.photoPath" />
</div>
<div class="col-xs-8">
.....
.....
.....
employee-details.component.ts
import { Component, OnInit } from '@angular/core';
import { Employee } from '../models/employee.model';
import { ActivatedRoute } from '@angular/router';
import { EmployeeService } from './employee.service';
@Component({
selector: 'app-employee-details',
templateUrl: './employee-details.component.html',
styleUrls: ['./employee-details.component.css']
})
export class EmployeeDetailsComponent implements OnInit {
employee: Employee;
constructor(private _route: ActivatedRoute,
private _employeeService: EmployeeService) { }
ngOnInit() {
const id = +this._route.snapshot.paramMap.get('id');
this.employee = this._employeeService.getEmployee(id);
}
}