Angular Material Table-异步数据源问题

时间:2018-11-07 16:11:28

标签: angular angular-material angular-material2 angular-material-6

我正在尝试用从AWS DynamoDB异步加载的数据填充Angular Material表,但是我能做的最好的事情是渲染具有三个预期项目的表,这些预期项在每个单元格中都将属性返回为“ [object Object]”。

该过程如下:

  • 在AllInvoicesComponent.ngOnInit()处,执行buildTable(),
  • 等待DataService.getItems('invoices'),
  • 将dataSource分配为新的MatTableDataSource(AllInvoicesComponent.invoices)

“异步”管道也对dataSource的{​​{1}}属性完全不起作用。

data.service.ts:

table

all-invoices.component.ts:

import { Injectable } from '@angular/core';
import * as aws from 'aws-sdk';
import { Observable } from 'rxjs';
import AuthService from '@app/services/auth.service';

@Injectable({
  providedIn: 'root'
})

export class DataService {

  dynamodb;
  docClient;

  constructor(private auth: AuthService) {
    aws.config.credentials = new aws.Credentials(auth.credentials.accessKeyId, auth.credentials.secretAccessKey, null);
    aws.config.update({
        region: 'eu-west-1'
    })

    this.dynamodb = new aws.DynamoDB();
    this.docClient = new aws.DynamoDB.DocumentClient();
  }

  async getItems(tableName) {
    const params = {
        TableName: tableName
    }

    return new Promise((resolve, reject) => {
        this.dynamodb.scan(params, (err, data) => {
            if (err) {
                reject(err);
            } else {
                resolve(data.Items);
            }
        })
    })
  }
}

all-invoices.component.html:

import { Component, OnInit, ViewChild } from '@angular/core';
import { Observable, from } from 'rxjs';
import {MatPaginator, MatSort, MatTableDataSource} from '@angular/material';

import Invoice from '../invoice.interface';
import { DataService } from '../../services/data/data.service';

@Component({
  selector: 'app-all-invoices',
  templateUrl: './all-invoices.component.html',
  styleUrls: ['./all-invoices.component.scss']
})

export class AllInvoicesComponent implements OnInit {

  invoices;

  dataSource: MatTableDataSource<any>;
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  tableColumns = [
    'number',
    'reference'
  ]

  constructor(private database: DataService) {

  }

  ngOnInit() {
    this.buildTable();
  }

  async buildTable() {
    try {
        this.invoices = await this.database.getItems('invoices');
        this.dataSource = new MatTableDataSource(this.invoices);
    } catch(err) {
        console.error(`Error retrieving invoices: ${err.Message}`);
        // TODO:
    }
  }

}

2 个答案:

答案 0 :(得分:0)

您正在将new MatTableDataSource(this.invoices);分配给this.dataSource.data,但是数据对象仅仅是原始数据。因此,只需将代码修复为

this.dataSource = new MatTableDataSource(this.invoices);

你应该很好。

提示: MatTable数据源不必是MatTableDataSource元素。您可以仅将原始数据传递到[dataSource]属性。

答案 1 :(得分:0)

DYNAMODB!

这是DynamoDB无意义地将对象的每个属性返回为同时包含值和字段类型作为属性的对象的结果。