角度材料数据表 - 无法排序或分页但是可以查看并且可以过滤

时间:2018-03-25 14:22:03

标签: angular typescript

可以正确查看表格并过滤数据。来自JSON的数据源的来源。分页和排序不起作用。控制台出错:

TypeError:无法设置属性' paginator'在ProductListComponent.ngAfterViewInit中未定义。

尝试过定义paginator的不同点(在构造函数中等),但这个点让我的脖子发了起来。

<CommandBar>
    <AppBarToggleButton Style="{StaticResource LabelOnlyAppBarToggleButtonStyle}" Label="This is a very long label" />
</CommandBar>

&#13;
&#13;
    product-list-component.ts
    product-list-component.html
&#13;
import { Component, ViewChild } from '@angular/core';
import { AfterViewInit } from '@angular/core';
import { GlobalService } from '../../services/global.service';
import { Router } from '@angular/router';
import { ProductService } from '../../services/product.service';
import { Subscription } from 'rxjs/Subscription';
import { User } from '../../models/user';
import { MatTableDataSource, MatPaginator, MatSort } from '@angular/material';
import { Product } from '../../models/product';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.css'],
  providers: [ProductService]
})
export class ProductListComponent implements AfterViewInit {
  // JB This dictates the order of the fields displayed on the Mat tables
  displayedColumns = ['id', 'sku', 'name', 'description'];
  dataSource: MatTableDataSource<Product>;
  products;
  // JB Used to see if user can access page
  account: User = new User();
  userSub: Subscription;

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  constructor(private global: GlobalService,
    private router: Router,
    private productService: ProductService) { }

  ngOnInit() {
    this.userSub = this.global.user.subscribe(
      me => this.account = me
    );
    if ( localStorage.getItem('token') && localStorage.getItem('account')) {
      this.global.me = JSON.parse(localStorage.getItem('account'));
      this.getProducts();
      // this.dataSource = new MatTableDataSource(this.getProducts());
    } else {
      this.router.navigate(['/login']);
      // this.router.navigateByUrl(['/#/authenticatin/login']);
    }
  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  }
  getProducts() {
    this.productService.getProducts().subscribe(
      response => {
        this.products = response;
        this.dataSource = new MatTableDataSource(response);
        console.log('products', response);
      },
      error => {
        console.log('error', error);
        // this.snackBar.open('Error getting movies JB...', '', { duration: 3000});
      }
    );
  }
}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

您尝试访问dataSource中的ngAfterViewInit,但在此阶段dataSource可能尚未设置,因为在productServices.getProducts()完成时已分配ngAfterViewInit可能在 getProducts() { this.productService.getProducts().subscribe( response => { this.dataSource = new MatTableDataSource(response); this.dataSource.paginator = this.paginator;

之后

您可以在订阅方法

中创建表格后分配分页器
paginator

但是,在 constructor() { this.dataSource = new MatTableDataSource([]); } //... getProducts() { this.productService.getProducts().subscribe( response => { this.dataSource.data = response as Product[]; 设置

之前,调用仍然存在风险

另一个解决方案是在构造函数中创建一个空数据源,像你已经设置的那样设置paginator,但只更新你订阅中的数据

func returnUIColor(components: String) -> UIColor {
    let scanner = Scanner(string: components)
    let skipped = CharacterSet(charactersIn: "[], ")
    let comma = CharacterSet(charactersIn: ",")
    scanner.charactersToBeSkipped = skipped

    var r, g, b, a : NSString?

    scanner.scanUpToCharacters(from: comma, into: &r)
    scanner.scanUpToCharacters(from: comma, into: &g)
    scanner.scanUpToCharacters(from: comma, into: &b)
    scanner.scanUpToCharacters(from: comma, into: &a)

    let defaultColor = UIColor.lightGray

    guard let rUnwrapped = r else { return defaultColor }
    guard let gUnwrapped = g else { return defaultColor }
    guard let bUnwrapped = b else { return defaultColor }
    guard let aUnwrapped = a else { return defaultColor }

    let rfloat = CGFloat(rUnwrapped.doubleValue)
    let gfloat = CGFloat(gUnwrapped.doubleValue)
    let bfloat = CGFloat(bUnwrapped.doubleValue)
    let afloat = CGFloat(aUnwrapped.doubleValue)

    let newUIColor = UIColor(red: rfloat, green: gfloat, blue: bfloat, alpha: afloat)
    return newUIColor
}

答案 1 :(得分:0)

在隐藏了Mat-table的html中删除任何* ngIf,可能会解决问题