【问题标题】:Data from web api and it's not Display in Html page来自 web api 的数据,它不在 Html 页面中显示
【发布时间】:2018-05-26 23:00:14
【问题描述】:

我尝试创建一个简单的 Angular 应用程序。我正在尝试从 web api 获取数据。问题是数据到达前端(console.log(DataObeject)。

这是我的 service.ts

     employerApiUrl = 'http://localhost:63858/api/';

    //private url: UrlConst;
    constructor(private _httpClient: HttpClient) { }

    // get all employee list

    getAllEmployee(): Observable<Employer>  {
        return this._httpClient.get<Employer>(this.employerApiUrl + 'Employe/getAllEmploye');
    }
}

这里是我的组件 ts

export class EmployerVeiwComponent implements OnInit {

  EmployerList;
  constructor(private _employerDetails: EmployerService) { }

  ngOnInit() {
    this.getEmployee();
  }

  // getting employee data from service 
  getEmployee() {
    this._employerDetails.getAllEmployee()
      .subscribe(
        employerList => employerList = this.EmployerList);
  }
}

这里是我的 html

<table class="table table-condensed">
    <thead>
      <tr>
        <th>Employer ID</th>
        <th>Firs Name</th>
        <th>Last Name <button>&#x2191;</button></th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor = "let employer of EmployerList">
        <td>{{ employer.ID }}</td>

      </tr>
    </tbody>
  </table>

问题来了

这里是控制台结果

它在来自 API 的记录数量表中创建条形图。

【问题讨论】:

    标签: angular


    【解决方案1】:

    问题很少

    (i) 你需要将数组初始化为,

    EmployerList : any =[];
    

    (ii)将结果分配给 EmployerList 为,

    getEmployee() {
        this._employerDetails.getAllEmployee()
          .subscribe(
            employerList => this.EmployerList = employerList );
    }
    

    (iii) 在模板中也应该是 id 而不是 ID

    <tr *ngFor = "let employer of EmployerList">
         <td>{{ employer.id}} : {{employer.fname}}</td>
    </tr>
    

    【讨论】:

    • 奇怪!你确定你得到了结果吗?添加一个 console.log(this.EmployerList) 并查看
    • 是的。我在控制台中看到了结果。控制台打印所有数据
    • 你能把结果贴在这里吗? console.log(JSON.stringify(this.EmployerList));
    • 我添加了控制台结果
    • 名称正在运行。但 id 不是显示。我如何显示 ID?
    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 2022-11-21
    • 2021-01-18
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多