如何以角度显示Model属性名称而不是Json键名称?

时间:2018-09-12 09:34:35

标签: angular typescript

我有一个Employee定义的模型接口:

export interface Employee {
   Name: string;
   Joining:string;
   Team: string;
   Manager: string;
   Position: string;
   Rating: string;
}

我可以通过以下格式调用Api从服务中获取值:

{
  employee_name: "James", joining_year: "2004", employee_rating: "", job_position: "Network Staff Member", manager_name: "Joel", team_name: "Network"
}

我想显示模型的属性名称,而不是Json键名称。 当前它显示如下:

employee_name    joining_year  manager_name
   James              2004           Joel

我想显示为:

Name               Joining          Manager  
James                2004              Joel

我通过这种方式得到json响应:

this._employeeService.getData()
  .subscribe(response => {
        this.empInfo = <Employee>response;
   });

我尝试过的事情:

获取列数据:

 Object.keys(this.empInfo[0]).forEach((item: string) => {
    this.columns.push({ title: item});
});

模板代码:

<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>

2 个答案:

答案 0 :(得分:1)

您可以在getData方法内映射数据:

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
        }
      }
    )
});

答案 1 :(得分:0)

您可以通过map

将数据映射到您的班级

所以,在您的getData()

getData() {
  return this._http.get('url')
    .map((response: Response) => response.json().map(res => new Employee(res.employee_name, res.joining_year, manager_name)));
  }

您的课程有一个构造函数

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....
    }
}