Angular 2+ 在从 api 获取数据时用 ngFor 填充 html table

Angular 2+ filling an html table with ngFor when data is get from api

我对 Angular 很陌生,所以虽然我正在努力完成一些事情,但我想这并不困难,但我遇到了困难,需要你的帮助。

我需要做的是在单击按钮时以及从 api 调用接收到数据后,用客户数据填充 html table。

如果我将数据定义为 TypeScript class 的 public 属性,我可以使用 ngFor 显示 "fixed" 数据,如 clientsData1 所示(我留作示例),但不能将 ngFor 绑定到包含 json 结果(clientsData)更改的变量。

简而言之,我要做的是当我单击按钮时启动 getItems 方法,一旦 getItems 有结果我就需要更新 table.

这是我的 TypeScript class:

import {Component} from '@angular/core';
import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable }     from 'rxjs/Observable';

import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/toPromise';

@Injectable()
@Component({
  selector: 'demo-app',
  templateUrl: 'app/views/app.component.html'
})
export class AppComponent {
  public clientsData : string;
  private clientsUrl : string = 'http://www.mocky.io/v2/5808862710000087232b75ac';
  public clientsData1 : any = [{'id': 1}, {'id': 3}, {'id': 5}];
  constructor (private http: Http) { }
  ngOnInit() {
    let btnGetClients = document.getElementById("btnGetClients");
    btnGetClients.addEventListener("click", (e:Event) => this.getItems()
        .subscribe(
          ipdata => this.clientsData = ipdata.clientsJson
        ));
  }  
  getItems(): Observable<IPData> {    
        return this.http.get(this.clientsUrl)
                        .map(this.extractData);
  }
  extractData(res: Response) {
    return res.json();
  }
}
class IPData {
  public clientsJson : string;
}

这是 html 模板:

<h1>Insurance App</h1>
<hr />
<button id="btnGetClients">Get Clients</button>
<br/><br/>
<table>
    <thead>
        <th>Id</th>
        <th>Name</th>
        <th>Email</th>
        <th>Role</th>
    </thead>
    <tbody *ngFor="let client of clientsData">
        <tr>
            <td>{{client.id}}</td>
        </tr>
    </tbody>
</table>

任何帮助将不胜感激。

谢谢。

首先,在 TS 文件中使用任何 DOM 操作都是不好的做法。您可以像这样添加点击事件处理程序

<button (click)='getItemsSubscription()'>Get Clients</button>

要遍历创建组件时不存在的数组,您需要像这样使用 ngFor

 <tbody *ngFor="let client of clientsData">
        <tr>
            <td>{{client?.id}}</td>
        </tr>
 </tbody

客户端带有引号。引号意味着当您在组件词法环境中拥有数据时,您将获得数据呈现,或者根本不会呈现它。

如果您想通过单击按钮调用数据,还有一件事。当你调用一个函数时,你并没有订阅它,所以你需要将它包装起来并做这样的事情

  getItemsSubscription() {
       this.getItems().subscribe(
              ipdata => this.clientsData = ipdata.clientsJson
        }
  }