Reputation: 278
I have a model interface Employee defined:
export interface Employee {
Name: string;
Joining:string;
Team: string;
Manager: string;
Position: string;
Rating: string;
}
I get the values from a service by calling an Api in the following format:
{
employee_name: "James", joining_year: "2004", employee_rating: "", job_position: "Network Staff Member", manager_name: "Joel", team_name: "Network"
}
I want to display the Property name of models instead of the Json key names. Currently it is displayed like this:
employee_name joining_year manager_name
James 2004 Joel
I want to show it like:
Name Joining Manager
James 2004 Joel
I am getting the json response this way:
this._employeeService.getData()
.subscribe(response => {
this.empInfo = <Employee>response;
});
Something I tried:
Getting the data for columns:
Object.keys(this.empInfo[0]).forEach((item: string) => {
this.columns.push({ title: item});
});
Template code:
<div class='panel panel-primary'>
<div class='panel-heading'>
{{pageTitle}}
</div>
<div class='panel-body'>
<div class='table-responsive'>
<table class='table'>
<thead>
<tr>
<th *ngFor="let column of columns">
{{column.title}}
</th>
</tr>
</thead>
<tbody>
<tr *ngFor='let employee of empInfo'>
<td>{{ employee?.employee_name }}</td>
<td>{{ employee?.joining_year }}</td>
<td>{{ employee?.manager_name }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
Upvotes: 4
Views: 3567
Reputation: 626
You can map your data inside the getData method:
this._employeeService.getData()
.subscribe(response => {
this.empInfo = response.map(
employee => {
return {
Name: employee.employee_name,
Joining: employee.joining_year,
Rating: employee.employee_rating,
Position: employee.job_position,
Manager: employee.manager_name,
Team: employee.team_name
}
}
)
});
Upvotes: 3
Reputation: 7204
You can map your data to your class by map
So , in your getData()
getData() {
return this._http.get('url')
.map((response: Response) => response.json().map(res => new Employee(res.employee_name, res.joining_year, manager_name)));
}
and your class has a constructor
public interface IEmployee
{
Name: string;
Joining:string;
Team: string;
Manager: string;
Position: string;
Rating: string;
}
public class Employee extends IEmployee {
constructor(
public name: string,
public year: string,
public manager: string
)
{
//set properties....
}
}
Upvotes: 0