我有一个应用程序,用户可以在下拉菜单中进行选择以触发请求,并在网站上显示输出(在这种情况下为表格)。数据始终采用JSON
格式,如下所示:
'{"columns":["C1","C2"], "data":[[8,98],[22,95],[43,29],[79,29]]}';
'{"columns":["foo","bar","xyz"], "data":[[27,26,3],[54,80,93],[92,10,90]]}';
在jQuery
的世界中,我总是可以这样做:
table = $("#a_nice_table").DataTable({
data: response.data,
columns: response.columns
});
,该表显示在名为div
的{{1}}中。
我现在想在Angular中做同样的事情,但是要与网站的数量作斗争。
我有一个像这样的组件a_nice_table
:
dt-dropdown.component
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-dt-dropdown',
templateUrl: './dt-dropdown.component.html',
styleUrls: ['./dt-dropdown.component.css']
})
export class DtDropdownComponent implements OnInit {
ddSelector: string = "";
response: any;
tableJSON1: string = '{"columns":["C1","C2"], "data":[[8,98],[22,95],[43,29],[79,29]]}';
tableJSON2: string = '{"columns":["foo","bar","xyz"], "data":[[27,26,3],[54,80,93],[92,10,90]]}';
constructor(private http: HttpClient) { }
ngOnInit() { }
getTable() {
this.http.get('https://api.github.com/users/alan-agius4') // + this.ddSelector
.subscribe((response) => {
// usually without the if-clause
if (this.ddSelector === 'type1') {
this.response = JSON.parse(this.tableJSON1);
} else {
this.response = JSON.parse(this.tableJSON2);
}
// this.response = response;
console.log(response);
console.log(JSON.parse(this.tableJSON1));
});
}
}
子句现在仅用于演示目的;通常不需要这样做,if
将直接传递。
相应的response
如下所示:
HTML
但是,总会导致
错误TypeError:“ aoColumns [srcCol]未定义”
我如何正确执行此操作?
我想我不仅可以使用Choose something:
<select [(ngModel)]="ddSelector">
<option>type1</option>
<option>type2</option>
</select>
<button (click)="getTable()">Get table!</button>
<div *ngIf="response">
<table datatable class="row-border hover">
<thead>
{{ response.columns }}
</thead>
<tbody>
{{ response.data}}
</tbody>
</table>
</div>
和{{ response.columns }}
,还需要以某种方式循环,但不确定。
答案 0 :(得分:2)
尝试通过以下方式在HTML file
中显示数据:
<table datatable class="row-border hover">
<thead>
<tr>
<th *ngFor="let column of response.columns">
{{ column }}
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of response.data">
<td *ngFor="let cell of row">{{cell}}</td>
</tr>
</tbody>
</table>