【问题标题】:How to populate data on UI after reading from CSV file in Angular?从Angular中的CSV文件读取后如何在UI上填充数据?
【发布时间】:2020-05-31 08:44:31
【问题描述】:

我正在实现角度模板,并且正在读取 CSV 文件数据以将其显示在有组织的表格中。基于检索到的 csv 数据,我不擅长核心脚本部分。

我正在分享我的代码:

export class AppComponent implements OnInit{
  title = 'temp-app';

  public headers = [];
  public data = {};
  public strData = ''

  public selectedHeader = null;
  constructor(private fileSvc: FileService) {

  }

  ngOnInit(): void {
    this.fileSvc.getHeaders().subscribe(
      data => {
        if (data != null && data.length > 0) {
          let headers = data.split('\n');
          headers = headers.filter(x => x.trim() !== '');
          for (const item of headers) {
            this.headers.push(item.trim());
          }
          this.headers=[...new Set(this.headers)];         
        } else {
          this.headers = [];
        }
      }
    );

Service.ts

@Injectable({
  providedIn: 'root'
})
export class FileService {

  constructor(private httpClient: HttpClient) {

  }

  public getHeaders() {
    return this.httpClient.get('assets/data.csv', { responseType: 'text' });
  }

}

以上代码不正确: 我正在分享 UI,我正在接受什么。

data.csv

预期
1.代码首先应该读取第1列,即“AppName”,在读取第1列的所有行之后,它应该只保留唯一值并使用这些唯一值创建一个按钮。意味着 - 如果“LDAP”在第1列中多次出现,它应该只考虑一次“LDAP”并使用它应该创建一个按钮。 2. 同样,为第 1 列的所有剩余值创建按钮。

此处提供一个相关链接供参考:

https://stackblitz.com/edit/angular-ivy-ubcknl

提前致谢 将来我只想在列中显示相应的值。如果我点击 OAM 则会显示 OAM 列,如果我点击 LDAP 则会显示 LDAP 列值。

【问题讨论】:

    标签: javascript angular typescript export-to-csv


    【解决方案1】:

    假设您从资产文件夹中获取此数据。例如:-

    return this.httpClient.get('assets/tableContent.csv', { responseType: 'text' }).pipe((map(res)=> {
                           let columns= new Set(response.split('\n').map((item) => item.replace('\r', '').split(",")[0]));
                           let rows= response.split('\n'); 
                           let result obj = {
                                                 uniqueColumns: Array.from(columns),
                                                 data: {}
                                            }
                           columns.forEach((columnName) => {
                               obj.data['columnName'] = [];
                           });
                           rows.forEach((row) => {
                                  var rowItems = row.replace('\r', '').split(",");
                                  obj.data[rowItems[0]].push(rowItems.slice(1));
                           });
                           return obj;
    }));
    

    当您订阅它时,您将获得如下所示的对象:-

    {
      uniqueColumns: ['OAM','LDAP', 'myAccess', 'OAM', 'myLogin'],
      data: {
          'OAM': [
             ['DEV', 'OHS', 'Success'],
             ['Stage', 'OHS', 'Success']
           ],
           'LDAP': [
             ['DEV','MDS','FAIL'],
             ['DEV','DDNET','FAIL']
             //and other data
           ]
           //same for other columns
      }
    }
    

    通过上述数据结构,您可以使用 ngfor 指令轻松创建模板。

    例如:- 模板代码:-

    <table id="mainTable">
      <thead>
        <tr>
          <th *ngFor="let head of items.uniqueColumns">{{head}}</th>
        <tr>
      </thead>
      <tbody> 
        <tr>
          <td *ngFor="let head of items.uniqueColumns">
            <table id="columns">
              <tr>
                <td></td>
                <td *ngFor="let col of items.data[head]">
                  <ng-container *ngFor="let items of col">
                      <td >{{items}}</td>
                  </ng-container>
                </td>
              <tr>
              <tr>
                <td>Dev</td>
              </tr>
              <tr>
                <td>Stage</td>
              </tr>
            </table>
          </td>
        </tr>
      </tbody>
    </table>
    

    CSS :-

    table#mainTable,table#columns, th {
      border: 1px solid black;
    }
    #columns td {
      padding: 1em;
    }
    #columns>tr>td:not(:first-child) {
      border: 1px solid black;
    }
    #columns>tr>td:nth-child(2) {
      border-left: none;
    }
    
    #columns>tr:nth-child(1) {
      border-bottom: 1px solid black;
    }
    tr {
      padding: 1em;
    }
    
    table, td, th {
      border-collapse: collapse;
    }
    

    打字稿:-

    import { Component } from '@angular/core';
    import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      public items = {
      uniqueColumns: ['OAM','LDAP', 'myAccess', 'OAM', 'myLogin'],
      data: {
          'OAM': [
             ['DEV', 'OHS', 'Success'],
             ['Stage', 'OHS', 'Success']
           ],
           'LDAP': [
             ['DEV','MDS','FAIL'],
             ['DEV','DDNET','FAIL']
             //and other data
           ]
           //same for other columns
      }
    }
    }
    

    【讨论】:

    • 方法是完美的。但是我们如何在 UI 上渲染这是主要的症结......
    猜你喜欢
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 2013-05-12
    • 2017-01-02
    • 1970-01-01
    • 2011-02-22
    • 2017-04-17
    • 1970-01-01
    相关资源
    最近更新 更多