简体   繁体   English

如何使用ng-2表从静态JSON获取表https://github.com/valor-software/ng2-table.iam的数据

[英]how to get data from static JSON for table, https://github.com/valor-software/ng2-table.iam using ng-2 table

how to get data from json rather from table-data.ts iam confused.tried my best cant able to find the solution.where should i do alteration i think from private data:array=TableData; 我怎么能从json而不是从table-data.ts获取数据。我很困惑,无法找到解决方案。我应该在哪里做更改,我认为应该从私有数据中获取:array = TableData; It will be helpful if anyone give a solution. 如果有人提供解决方案,将很有帮助。

Demo.component.ts 演示组件

export class TableDemoComponent implements OnInit { public rows:Array<any> = [];
public columns:Array<any> = [
{title: 'Company', name: 'name', filtering: {filterString: '', placeholder: 'Filter by name'}},
{
  title: 'Position',
  name: 'position',
  sort: false,
  filtering: {filterString: '', placeholder: 'Filter by position'}
},
{title: 'Location', name: 'office', sort: '', filtering:     {filterString: '', placeholder: 'Filter by Location'}},
{title: 'Date', className: 'text-warning', name: 'startDate'},];
 public page:number = 1;
 public itemsPerPage:number = 10;
 public maxSize:number = 5;
 public numPages:number = 1;
 public length:number = 0;
 public config:any = {

paging: true,
sorting: {columns: this.columns},
filtering: {filterString: ''},
className: ['table-striped', 'table-bordered']
};
private data:Array<any> = TableData;
public constructor() {
this.length = this.data.length;
}
public ngOnInit():void {
this.onChangeTable(this.config);
}
public changePage(page:any, data:Array<any> = this.data):Array<any> {
let start = (page.page - 1) * page.itemsPerPage;
let end = page.itemsPerPage > -1 (startpage.itemsPerPage):data.length;
return data.slice(start, end);
}
public changeSort(data:any, config:any):any {
if (!config.sorting) {
  return data;
}
let columns = this.config.sorting.columns || [];
let columnName:string = void 0;
let sort:string = void 0;
for (let i = 0; i < columns.length; i++) {       if(columns[i].sort!==''&&columns[i].sort!==false{columnNamecolumns[i].name;
    sort = columns[i].sort;
  }
}
if (!columnName) {
  return data;
}
// simple sorting
return data.sort((previous:any, current:any) => {
  if (previous[columnName] > current[columnName]) {
    return sort === 'desc' ? -1 : 1;
  } else if (previous[columnName] < current[columnName]) {
    return sort === 'asc' ? -1 : 1;
  }
  return 0;
  });
  }
  public changeFilter(data:any, config:any):any {
  let filteredData:Array<any> = data;
  this.columns.forEach((column:any) => {
  if (column.filtering) {
  filteredData = filteredData.filter((item:any) => {
  return item[column.name].match(column.filtering.filterString); });
  }
  });
 if (!config.filtering) {
  return filteredData;
}
if (config.filtering.columnName) {
  return filteredData.filter((item:any) =>        item[config.filtering.columnName].match(this.config.filtering.filterString));
}
let tempArray:Array<any> = [];
filteredData.forEach((item:any) => {
  let flag = false;
  this.columns.forEach((column:any) => {
    if     (item[column.name].toString().match(this.config.filtering.filterString)) {
      flag = true;
    }
  });
  if (flag) {
    tempArray.push(item);
  }
});
filteredData = tempArray;
return filteredData;
}
public onChangeTable(config:any, page:any = {page:   this.page,itemsPerPage: this.itemsPerPage}):any {
if (config.filtering) {
  Object.assign(this.config.filtering, config.filtering);
}
if (config.sorting) {
  Object.assign(this.config.sorting, config.sorting);
}
let filteredData = this.changeFilter(this.data, this.config);
let sortedData = this.changeSort(filteredData, this.config);
this.rows = page && config.paging ?  this.changePage(page,sortedData):sortedData;
this.length = sortedData.length;
}
public onCellClick(data: any): any {
console.log(data);
}}

Datatable.ts 数据表

export const TableData:Array<any> = [
{
'name': 'Victoria Cantrell',
'position': 'Integer Corporation',
'office': 'Croatia',
'ext': `<strong>0839</strong>`,
'startDate': '2015/08/19',
'salary': 208.178
}, {
'name': 'Pearl Crosby',
'position': 'In PC',
'office': 'Cambodia',
'ext': `<strong>8262</strong>`,
'startDate': '2014/10/08',
'salary': 114.367
 }, {
'name': 'Colette Foley',
'position': 'Lorem Inc.',
'office': 'Korea, North',
'ext': '8968',
'startDate': '2015/07/19',
'salary': 721.473
}
];

Table-demo.html Table-demo.html

       <div class="row">
       <div class="col-md-4">
       <input *ngIf="config.filtering" placeholder="Filter allcolumns"
       [ngTableFiltering]="config.filtering"
       class="form-control"
       (tableChanged)="onChangeTable(config)"/>
       </div>
       </div>
       <br>
       <ng-table [config]="config"
       (tableChanged)="onChangeTable(config)"
       (cellClicked)="onCellClick($event)"
       [rows]="rows" [columns]="columns">
        </ng-table>
        <pagination *ngIf="config.paging"
        class="pagination-sm"
        [(ngModel)]="page"
        [totalItems]="length"
        [itemsPerPage]="itemsPerPage"
        [maxSize]="maxSize"
        [boundaryLinks]="true"
        [rotate]="false"
        (pageChanged)="onChangeTable(config, $event)"
        (numPages)="numPages = $event">
        </pagination>

If you wanted to use the TableData in a different file you would have to import it. 如果要在其他文件中使用TableData ,则必须将其导入。 I have added an example at the top that show you how to import it. 我在顶部添加了一个示例,向您展示了如何导入它。 All you do is just create another file and import what you need. 您要做的只是创建另一个文件,然后导入所需的文件。 I tidied up your code and fixed some syntax errors and put some notes next to bits where stuff was undefined which would throw errors also put some explanations next to the top in how to import things: 我整理了代码并修复了一些语法错误,并在未定义内容的位旁边添加了一些注释,这些位会引发错误,并且在如何导入内容的顶部也添加了一些说明:

import {OnInit} from "@angular/core"
import {TableData} from "./test2" //test2 is the name of the file

// ./ current directory
// ../../ up two directories

export class TableDemoComponent implements OnInit {
    public rows: Array<any> = [];

    public columns: Array<any> =
        [
            {
                title: 'Company',
                name: 'name',
                filtering: {
                    filterString: '', placeholder: 'Filter by name'
                }
            },
            {
                title: 'Position',
                name: 'position',
                sort: false,
                filtering: {
                    filterString: '', placeholder: 'Filter by position'
                }
            },
            {
                title: 'Location',
                name: 'office',
                sort: '',
                filtering: {
                    filterString: '', placeholder: 'Filter by Location'
                }
            },
            {
                title: 'Date',
                className: 'text-warning',
                name: 'startDate'
            }
        ];

    public page: number = 1;
    public itemsPerPage: number = 10;
    public maxSize: number = 5;
    public numPages: number = 1;
    public length: number = 0;

    public config: any = {
        paging: true,
        sorting: {columns: this.columns},
        filtering: {filterString: ''},
        className: ['table-striped', 'table-bordered']
    };

    private data: Array<any> = TableData;

    public constructor() {
        this.length = this.data.length;
    }

    public ngOnInit(): void {
        this.onChangeTable(this.config);
    }

    public changePage(page: any, data: Array<any> = this.data): Array<any> {
        let start = (page.page - 1) * page.itemsPerPage;

        //startpage is not defined
        let end = page.itemsPerPage > -1 ? startpage.itemsPerPage : data.length;
        return data.slice(start, end);
    }

    public changeSort(data: any, config: any): any {
        if (!config.sorting) {
            return data;
        }

        let columns = this.config.sorting.columns || [];
        let columnName: string = void 0;
        let sort: string = void 0;

        for (let i = 0; i < columns.length; i++) {
            if (columns[i].sort !== '' && columns[i].sort !== false) {
                //columnNamecolumns is not defined
                columnNamecolumns[i].name;
                sort = columns[i].sort;
            }
        }

        if (!columnName) {
            return data;
        }

        // simple sorting
        return data.sort((previous: any, current: any) => {
            if (previous[columnName] > current[columnName]) {
                return sort === 'desc' ? -1 : 1;
            } else if (previous[columnName] < current[columnName]) {
                return sort === 'asc' ? -1 : 1;
            }
            return 0;
        });
    }

    public changeFilter(data: any, config: any): any {
        let filteredData: Array<any> = data;
        this.columns.forEach((column: any) => {
            if (column.filtering) {
                filteredData = filteredData.filter((item: any) => {
                    return item[column.name].match(column.filtering.filterString);
                });
            }
        });
        if (!config.filtering) {
            return filteredData;
        }
        if (config.filtering.columnName) {
            return filteredData.filter((item: any) => item[config.filtering.columnName].match(this.config.filtering.filterString));
        }
        let tempArray: Array<any> = [];
        filteredData.forEach((item: any) => {
            let flag = false;
            this.columns.forEach((column: any) => {
                if (item[column.name].toString().match(this.config.filtering.filterString)) {
                    flag = true;
                }
            });
            if (flag) {
                tempArray.push(item);
            }
        });
        filteredData = tempArray;
        return filteredData;
    }

    public onChangeTable(config: any, page: any = {page: this.page, itemsPerPage: this.itemsPerPage}): any {
        if (config.filtering) {
            Object.assign(this.config.filtering, config.filtering);
        }
        if (config.sorting) {
            Object.assign(this.config.sorting, config.sorting);
        }
        let filteredData = this.changeFilter(this.data, this.config);
        let sortedData = this.changeSort(filteredData, this.config);
        this.rows = page && config.paging ? this.changePage(page, sortedData) : sortedData;
        this.length = sortedData.length;
    }

    public onCellClick(data: any): any {
        console.log(data);
    }
}

I hope this is what you meant for. 我希望这就是你的意思。 I am reading my data from external source (not json - but I think this is the same) by this way: 我通过这种方式从外部源(不是json-但我认为这是相同的)读取数据:

public constructor(private dataService: DataService ){
      this.dataService.getUsers().then(users => {this.data = users; this.length = this.data.length;}).
         catch(error => this.error = error);
  }

  public ngOnInit():void {
       this.dataService.getUsers().then(users => {this.data = users;  this.onChangeTable(this.config);}).
         catch(error => this.error = error);
  }

in this example my data is users. 在此示例中,我的数据是用户。 I am calling it from my data service. 我正在从数据服务中调用它。 I hope it helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM