代码之家  ›  专栏  ›  技术社区  ›  Cleb

如何创建包含任意列和数据的数据表?

  •  0
  • Cleb  · 技术社区  · 6 年前

    我有一个应用程序,用户可以在一个下拉列表中进行选择,该下拉列表触发一个请求,输出(在本例中是一个表)显示在网站上。数据总是进来的 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 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 看起来像这样:

    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>
    

    然而,这总是导致

    错误类型错误:“aoColumns[srcCol]未定义”

    如何正确地执行此操作?

    我想我不能只用 {{ response.columns }} {{ response.data}}

    1 回复  |  直到 6 年前
        1
  •  2
  •   Jake11    6 年前

    尝试在中显示数据 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>