首页 > 解决方案 > 从剩余数据馈送角材料表 - 错误类型错误:无法读取未定义的属性“数据”

问题描述

我是角度的新手。现在我正在用 Angular (7) 开发一个原型。原型应使用来自外部页面 (AZURE) 的 rest 加载数据。我设法设置了请求,我可以看到控制台中提供的数据,但我不知道如何初始化 Material 表以使用响应的数据来构建表,我在互联网上找不到任何 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 错误类型错误:无法读取未定义的属性“数据”

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

感谢您的支持 :-)

标签: angularangular-material

解决方案


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

的全部要点length是要固定值,否则它将始终在一页上。所以只是放length="50"或其他。或者,如果您出于任何原因想要坚持长度,您可能想要[length]="accounts.length"

在您编辑和指定您的问题之前:您可以在官方 Angular 文档中找到各种带有相关代码的示例。

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


推荐阅读