从剩余数据中输入角材料表-错误TypeError:无法读取未定义的属性“数据”

时间:2019-01-12 11:53:52

标签: angular angular-material

我是新手。现在,我正在用Angular(7)开发原型。 原型应使用外部页面上的其余部分(AZURE)加载数据。我设法设置了请求,我可以看到控制台中提供的数据,但是我不知道如何初始化Material表以使用响应的数据来构建表,并且在Internet上找不到Angular版本的任何示例7。

我正在寻找一个代码示例,一旦我能设法理解就可以了。

这是响应中的JSON数据(我将其剪切以便使其适合帖子),我的ts文件是您在运行时获得的文件:

ng生成@ angular / material:material-table --name = accountlist

====accountlist.component.html====
 <div class="mat-elevation-z8">
  <table mat-table class="full-width-table" [dataSource]="accounts.data.Documents" matSort aria-label="Elements">
    <!-- Id Column -->
    <ng-container matColumnDef="ID">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>ID</th>
      <td mat-cell *matCellDef="let row">{{row.ID}}</td>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="Name">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th>
      <td mat-cell *matCellDef="let row">{{row.Name}}</td>
    </ng-container>

        <!-- City Column -->
        <ng-container matColumnDef="City">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>City</th>
            <td mat-cell *matCellDef="let row">{{row.City}}</td>
          </ng-container>

              <!-- Country Column -->
    <ng-container matColumnDef="Country">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>Country</th>
        <td mat-cell *matCellDef="let row">{{row.Country}}</td>
      </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>

  <mat-paginator #paginator
      [length]="accounts.data.Documents.length"
      [pageIndex]="0"
      [pageSize]="50"
      [pageSizeOptions]="[25, 50, 100, 250]">
  </mat-paginator>
</div>

====accountlist.comoponent.ts====
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, MatSort } from '@angular/material';
import { AccountlistDataSource } from './accountlist-datasource';
import { AzureService } from './../_services/azure.service';

@Component({
  selector: 'app-accountlist',
  templateUrl: './accountlist.component.html',
  styleUrls: ['./accountlist.component.css']
})
export class AccountlistComponent implements OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  dataSource: AccountlistDataSource;
  public accounts: any;

  constructor(private azureService: AzureService) {

  }

  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['ID', 'Name', 'City', 'Country'];

  readAccountsAzure(): void {
    this.azureService.getAccountsAzure()
      .subscribe(
        accounts => {
          this.accounts = accounts;
          console.log(this.accounts.Documents);
        }
      );
  }

  RenderDataTable() {
    this.azureService.getAccountsAzure()
      .subscribe(
      res => {
        this.accounts = new AccountlistDataSource(this.paginator, this.sort);
        this.accounts.data = res as Account[];
        console.log(this.accounts);
      },
      error => {
        console.log('There was an error while retrieving data !!!' + error);
      });
  }

  ngOnInit() {

    this.RenderDataTable();
   // this.accounts = new AccountlistDataSource(this.paginator, this.sort);
  }
}


====accountlist-datasource.ts====
import { AzureService } from './../_services/azure.service';
import { DataSource } from '@angular/cdk/collections';
import { MatPaginator, MatSort } from '@angular/material';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';

// TODO: Replace this with your own data model type
export interface AccountlistItem {
  name: string;
  id: number;
}

// TODO: replace this with real data from your application
const EXAMPLE_DATA: AccountlistItem[] = [
  {id: 1, name: 'Hydrogen'},
  {id: 2, name: 'Helium'},
  {id: 3, name: 'Lithium'},
  {id: 4, name: 'Beryllium'},
  {id: 5, name: 'Boron'},
  {id: 6, name: 'Carbon'},
  {id: 7, name: 'Nitrogen'},
  {id: 8, name: 'Oxygen'},
  {id: 9, name: 'Fluorine'},
  {id: 10, name: 'Neon'},
  {id: 11, name: 'Sodium'},
  {id: 12, name: 'Magnesium'},
  {id: 13, name: 'Aluminum'},
  {id: 14, name: 'Silicon'},
  {id: 15, name: 'Phosphorus'},
  {id: 16, name: 'Sulfur'},
  {id: 17, name: 'Chlorine'},
  {id: 18, name: 'Argon'},
  {id: 19, name: 'Potassium'},
  {id: 20, name: 'Calcium'},
];

/**
 * Data source for the Accountlist view. This class should
 * encapsulate all logic for fetching and manipulating the displayed data
 * (including sorting, pagination, and filtering).
 */
export class AccountlistDataSource extends DataSource<AccountlistItem> {
  // data: AccountlistItem[] = EXAMPLE_DATA;
data: AccountlistItem[];

  constructor(private paginator: MatPaginator, private sort: MatSort) {
    super();
  }

  /**
   * Connect this data source to the table. The table will only update when
   * the returned stream emits new items.
   * @returns A stream of the items to be rendered.
   */
  connect(): Observable<AccountlistItem[]> {
    // Combine everything that affects the rendered data into one update
    // stream for the data-table to consume.
    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];

    // Set the paginator's length
    this.paginator.length = this.data.length;

    return merge(...dataMutations).pipe(map(() => {
      return this.getPagedData(this.getSortedData([...this.data]));
    }));
  }

  /**
   *  Called when the table is being destroyed. Use this function, to clean up
   * any open connections or free any held resources that were set up during connect.
   */
  disconnect() {}

  /**
   * Paginate the data (client-side). If you're using server-side pagination,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getPagedData(data: AccountlistItem[]) {
    const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
    return data.splice(startIndex, this.paginator.pageSize);
  }

  /**
   * Sort the data (client-side). If you're using server-side sorting,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getSortedData(data: AccountlistItem[]) {
    if (!this.sort.active || this.sort.direction === '') {
      return data;
    }

    return data.sort((a, b) => {
      const isAsc = this.sort.direction === 'asc';
      switch (this.sort.active) {
        case 'name': return compare(a.name, b.name, isAsc);
        case 'id': return compare(+a.id, +b.id, isAsc);
        default: return 0;
      }
    });
  }
}

/** Simple sort comparator for example ID/Name columns (for client-side sorting). */
function compare(a, b, isAsc) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}


====JSON RESPONSE====
 {  
   "_rid":"R-UdANZutGw=",
   "Documents":[  
      {  
         "id":"c5826db5-d68b-4be8-84ed-c4cc3c15cd5a",
         "_rid":"R-UdANZutGwJAAAAAAAAAA==",
         "_self":"dbs\/R-UdAA==\/colls\/R-UdANZutGw=\/docs\/R-UdANZutGwJAAAAAAAAAA==\/",
         "_etag":"\"06000f28-0000-0c00-0000-5c34d2830000\"",
         "Account Number":"232342-555445",
         "Country":"Germany",
         "Created Date":"01/10/2018",
         "Currency":"US Dollar",
         "ID":"8adc8f99661fc13b01662f31eeb413dc",
         "Name":"85255-1545445",
         "SHS_SAP_SOLD_TO":"US_0000001234",
         "Status":"Active",
         "Address 1":"",
         "Address 2":"",
         "City":"",
         "County":"",
         "Postal Code":"",
         "State/Province":"",
         "_attachments":"attachments\/",
         "_ts":1546965635
      },
      {  
         "id":"1f990cdf-d64c-49d4-b6bc-4fdc91462d2c",
         "_rid":"R-UdANZutGwvAQAAAAAAAA==",
         "_self":"dbs\/R-UdAA==\/colls\/R-UdANZutGw=\/docs\/R-UdANZutGwvAQAAAAAAAA==\/",
         "_etag":"\"06003529-0000-0c00-0000-5c34d2830000\"",
         "Account Number":"90164412-100532",
         "Country":"Germany",
         "Created Date":"01/10/2018",
         "Currency":"US Dollar",
         "ID":"8adce421661fcddc01662f3263836dfb",
         "Name":"15151-45100532",
         "SHS_SAP_SOLD_TO":"US_0000001234",
         "Status":"Active",
         "Address 1":"",
         "Address 2":"",
         "City":"",
         "County":"",
         "Postal Code":"",
         "State/Province":"",
         "_attachments":"attachments\/",
         "_ts":1546965635
      },
      {  
         "id":"185e8238-2287-4989-b7f1-d69ffa4f65fe",
         "_rid":"R-UdANZutGwwAQAAAAAAAA==",
         "_self":"dbs\/R-UdAA==\/colls\/R-UdANZutGw=\/docs\/R-UdANZutGwwAQAAAAAAAA==\/",
         "_etag":"\"06003629-0000-0c00-0000-5c34d2830000\"",
         "Account Number":"3432423-324234",
         "Country":"Germany",
         "Created Date":"01/10/2018",
         "Currency":"US Dollar",
         "ID":"8adce421661fcddc01662f3242d86dda",
         "Name":"23432423-324234",
         "SHS_SAP_SOLD_TO":"US_0000001234",
         "Status":"Active",
         "Address 1":"",
         "Address 2":"",
         "City":"",
         "County":"",
         "Postal Code":"",
         "State/Province":"",
         "_attachments":"attachments\/",
         "_ts":1546965635
      },
      {  
         "id":"7894ab52-9d3d-498d-a162-c9b57702c650",
         "_rid":"R-UdANZutGwxAQAAAAAAAA==",
         "_self":"dbs\/R-UdAA==\/colls\/R-UdANZutGw=\/docs\/R-UdANZutGwxAQAAAAAAAA==\/",
         "_etag":"\"06003729-0000-0c00-0000-5c34d2830000\"",
         "Account Number":"234234-234234",
         "Country":"Germany",
         "Created Date":"01/10/2018",
         "Currency":"US Dollar",
         "ID":"8adce421661fcddc01662f323f406dd6",
         "Name":"234234-234234",
         "SHS_SAP_SOLD_TO":"US_0000001234",
         "Status":"Active",
      },
      {  
         "id":"f274b1e9-7bac-48e8-8931-e98b7e8be046",
         "_rid":"R-UdANZutGzvAwAAAAAAAA==",
         "_self":"dbs\/R-UdAA==\/colls\/R-UdANZutGw=\/docs\/R-UdANZutGzvAwAAAAAAAA==\/",
         "_etag":"\"0600f52b-0000-0c00-0000-5c34d2890000\"",
         "Account Number":"324234-23423",
         "Country":"Germany",
         "Created Date":"01/10/2018",
         "Currency":"US Dollar",
         "ID":"8adc8f99661fc13b01662f34da211779",
         "Name":"Default Account",
         "SHS_SAP_SOLD_TO":"US_0000001234",
         "Status":"Active",
         "Address 1":"",
         "Address 2":"",
         "City":"",
         "County":"",
         "Postal Code":"",
         "State/Province":"",
         "_attachments":"attachments\/",
         "_ts":1546965641
      },
      {  
         "id":"415ff345-5ecd-4bfd-b20b-fd8cc7186744",
         "_rid":"R-UdANZutGzwAwAAAAAAAA==",
         "_self":"dbs\/R-UdAA==\/colls\/R-UdANZutGw=\/docs\/R-UdANZutGzwAwAAAAAAAA==\/",
         "_etag":"\"0600f62b-0000-0c00-0000-5c34d2890000\"",
         "Account Number":"324234-234234",
         "Country":"Germany",
         "Created Date":"01/10/2018",
         "Currency":"US Dollar",
         "ID":"8adc8f99661fc13b01662f34cc801765",
         "Name":"324234234",
         "SHS_SAP_SOLD_TO":"US_0000001234",
         "Status":"Active",
         "Address 1":"",
         "Address 2":"",
         "City":"",
         "County":"",
         "Postal Code":"",
         "State/Province":"",
         "_attachments":"attachments\/",
         "_ts":1546965641
      }
   ],
   "_count":1000
}

控制台日志显示第16行的HTML文件中存在错误。 AccountlistComponent.html:16错误TypeError:无法读取未定义的属性“数据”

但是我认为问题实际上与数据可能无法正确加载的事实有关

感谢您的支持:-)

2 个答案:

答案 0 :(得分:1)

该错误消息告诉您它无法从data读取undefined。这意味着,查看您的HTML代码,[length]="dataSource.data.length"失败了,因为dataSource没有被初始化。

length的全部要为固定值,否则它将始终在一页上。因此,只需放入length="50"或其他任何内容。或者,如果出于任何原因要坚持使用长度,则可能需要[length]="accounts.length"

在编辑并指定问题之前: 您可以在official Angular documentation中找到各种带有相关代码的示例。

您拥有数据,因此只需使用正确的MatTableDataSource成员在组件代码中正确设置变量即可。

答案 1 :(得分:0)

您忘记在 dataSource 中初始化 data 变量。因此,在页面加载时,它会发现 dataSource.data 未定义并引发错误。在您的ngOnInit()中,为 dataSource 初始化 data 变量。

ngOnInit() {
    dataSource.data = [];
    . . .
}