将 ELEMENT_DATA: PeriodicElement[] (mat-table) 移动到 Angular 中的另一个文件

Move ELEMENT_DATA: PeriodicElement[] (of mat-table) to another file in Angular

我正在构建一个 table 使用 Material 设计样式数据-table for Angular (doc) 我想传输数据:

    const ELEMENT_DATA: PeriodicElement[] = [
      {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
      {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
      {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
      {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
      {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
      {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
      {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
      {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
      {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
      {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
    ];

到一个单独的文件。我手动输入数据(和 Excel 但这不是重点)并且经常需要更改它并且对于每次更改我都必须编译整个应用程序。

如果我能把新的数据文件粘贴到服务器上就好了。

我试图创建一个新的 .json 文件,将其导入 app.component.ts 但这导致了很多错误并放弃了。

你可以查看我的测试版here

为了实现以上目标,

创建服务 - table.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class TableDataService{
  public getTableData(){
     this.http.get<any>("your file in server -url");
  }
}

现在在你的组件中

import { TableDataService} from 'table.service';
datasource;
constructor(private tableService:TableDataService){}

ngOnInit(){
this.tableService.getTableData.subscribe(res=>{
     this.dataSource = new MatTableDataSource<Element>(res);
});
}

在 HTML:

因此 table 只有在加载数据时才会显示

<mat-table #table *ngIf="dataSource" [dataSource]="dataSource">

这些链接会对您有所帮助

https://stackblitz.com/edit/read-local-json-file?file=src%2Fapp%2Fapp.component.ts https://stackblitz.com/edit/angular-material-table-data-source?file=app%2Fapp.component.html

我终于搞定了! 第一个创建的服务:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class UserService {

  constructor(private http: HttpClient) { }

  getUsers() {
    return this.http.get('https://ohipo.pl/assets/oferty.json');
  }
}

然后在app.component.ts

中获取下载数据
  ngOnInit() {
    this.userService.getUsers()
      .subscribe((users: User[]) => {
        this.users = users;
        this.dataSource = new MatTableDataSource(users);
        this.dataSource.sort = this.sort;
        console.log("users: " + users);
        console.log("dataSource1" + this.dataSource);
      });

值得一提的是,这个 StackBlitz 项目对我帮助很大:

https://stackblitz.com/edit/angular-material-table-modal?file=src%2Fapp%2Ftable.component.ts