Angular matSort 不排序 [英] Angular matSort does not sort

查看:20
本文介绍了Angular matSort 不排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将 matSort 导入 matTable 时遇到问题.

我正在向您提供我的代码:

dashboard.component.ts

import {Component, ViewChild} from '@angular/core';从../user.service"导入{UserService};从../dohvat-mantisa.service"导入{DohvatMantisaService};从../Mantisi"导入{Mantisi};从rxjs/Observable"导入{Observable};从@angular/cdk/collections"导入{DataSource};导入 'rxjs/add/observable/of';导入 'rxjs/add/operator/startWith';导入 'rxjs/add/observable/merge';从@angular/material"导入{MatSort};@成分({选择器:应用仪表板",templateUrl: './dashboard.component.html',styleUrls: ['./dashboard.component.css']})导出类仪表板组件{displayColumns = ['projekt', 'manits', 'kategorija','ozbiljnost','datum_prijave','postavio','odjel','postavio','naziv','status','planirana_isporuka'];构造函数(私有用户:UserService,私有 dohvatMantisa:DohvatMantisaService){}数据源:TableDataSource |空值;螳螂:螳螂[];name = this.user.getUsername();@ViewChild(MatSort) 排序:MatSort;ngOnInit() {this.dataSource = new TableDataSource(this.dohvatMantisa,this.sort);}}导出类 TableDataSource 扩展了 DataSource{构造函数(私有螳螂:DohvatMantisaService,私有排序:MatSort){极好的();}connect(): Observable{const displayDataChanges = [this.mantisiDS.dohvatiMantise(),this.sort.sortChange,];return Observable.merge(...displayDataChanges).map(() => {返回 this.getSortedData();});}断开连接(){}getSortedData(): Mantisi[]{const 数据 = this.mantisiDS.prikazMantisa().slice();if (!this.sort.active || this.sort.direction == '') { 返回数据;}返回 data.sort((a, b) => {让 propertyA: number|string = '';让 propertyB: number|string = '';开关(this.sort.active){case 'projekt': [propertyA, propertyB] = [a.projekt, b.projekt];休息;case 'manits': [propertyA, propertyB] = [a.manits, b.manits];休息;case 'kategorija': [propertyA, propertyB] = [a.kategorija, b.kategorija];休息;case 'ozbiljnost': [propertyA, propertyB] = [a.ozbiljnost, b.ozbiljnost];休息;case 'datum_prijave': [propertyA, propertyB] = [a.datum_prijave, b.datum_prijave];休息;case 'postavio': [propertyA, propertyB] = [a.postavio, b.postavio];休息;case 'naziv': [propertyA, propertyB] = [a.naziv, b.naziv];休息;case 'status': [propertyA, propertyB] = [a.status, b.status];休息;case 'planirana_isporuka': [propertyA, propertyB] = [a.planirana_isporuka, b.planirana_isporuka];休息;}让 valueA = isNaN(+propertyA) ?属性A:+属性A;让 valueB = isNaN(+propertyB) ?属性B:+属性B;return (valueA < valueB ? -1 : 1) * (this.sort.direction == 'asc' ? 1 : -1);});}}

这是我的服务:dohvatMantisaService

import { Injectable } from '@angular/core';从@angular/http"导入 {Http, Response, RequestOptions, Headers};从rxjs/Observable"导入{Observable};从./Mantisi"导入{Mantisi};导入'rxjs';导入 'rxjs/operator/map';导入 'rxjs/operator/do';@Injectable()导出类 DohvatMantisaService {构造函数(公共 http:Http){}结果:Mantisi[];dohvatiMantise(): Observable{return this.http.get('/mantis/getMantisReport').map(this.extractData);}私人提取数据(响应:响应){让 body = response.json();返回正文 ||{};}prikazMantisa(): Mantisi[]{this.dohvatiMantise().subscribe(res => this.result = res);返回 this.result;}}

我为您提供了我的dashboard.component.html matSort 行:

这里的主要问题是数据是从 http 请求中加载和获取的,但我在控制台中收到类似这样的错误:

<块引用>

无法读取未定义的属性sortChange"在 TableDataSource.webpackJsonp.../../../../../src/app/dashboard/dashboard.component.ts.TableDataSource.connect (dashboard.component.ts:36)在 MatTable.webpackJsonp.../../../cdk/esm5/table.es5.js.CdkTable._observeRenderChanges (table.es5.js:602)在 MatTable.webpackJsonp.../../../cdk/esm5/table.es5.js.CdkTable.ngAfterContentChecked (table.es5.js:522)

它告诉我 this.sort.sortChange 是未定义的.我搜索了所有互联网并找不到正确的答案.希望你能帮我解决这个问题.

解决方案

我已经找到了解决这个问题的方法.

主要问题是表格在数据到达之前呈现.我首先加载了数据并将其像源一样发送到 dataSource 构造函数.之后,问题就消失了.这就是异步 http.get 和服务的问题.

感谢您的帮助.

fetchData(id){this.fetch.getProcesses(id).subscribe(result => {this.processes = 结果;this.dataSource = new TableDataSource(this.processes);Observable.fromEvent(this.filter.nativeElement, 'keyup').去抖动时间(150).distinctUntilChanged().subscribe(() => {如果(!this.dataSource){返回;}this.dataSource.filter = this.filter.nativeElement.value;});});}导出类 TableDataSource 扩展了 DataSource{_filterChange = new BehaviorSubject('');获取过滤器():字符串{返回 this._filterChange.value;}设置过滤器(过滤器:字符串){this._filterChange.next(filter);}过滤数据:任何=[];构造函数(私有进程:进程[]){极好的();}连接():Observable{const displayDataChanges = [这个过程,this._filterChange,];return Observable.merge(...displayDataChanges).map(() => {this.filteredData = this.processes.slice().filter((item: Proces) => {const searchStr = (item.name).toLowerCase();返回 searchStr.indexOf(this.filter.toLowerCase()) !== -1;});返回 this.filteredData;})}断开(){}}<div class="header"><mat-form-field floatPlaceholder="never"><input matInput #filter placeholder="Pretraži procese"></mat-form-field>

<mat-table #table [dataSource]="dataSource" class="table-mantis" matSort><ng-container matColumnDef="col1"><mat-h​​eader-cell *matHeaderCellDef class="table-header-cell" mat-sort-header>名称</mat-h​​eader-cell><mat-cell *matCellDef="let row" class="example-cell" >{{row.nazivProcesa}} </mat-cell></ng-容器><ng-container matColumnDef="col2"><mat-h​​eader-cell *matHeaderCellDef class="table-header-cell" mat-sort-header>单元2</mat-h​​eader-cell><mat-cell *matCellDef="let row" class="example-cell" >{{row.nazivVlasnika}} </mat-cell></ng-容器><ng-container matColumnDef="col3"><mat-h​​eader-cell *matHeaderCellDef class="table-header-cell" mat-sort-header>单元3<mat-cell *matCellDef="let row" class="example-cell" >{{row.interniAkt}} </mat-cell></ng-容器><mat-h​​eader-row *matHeaderRowDef="displayedColumns" class="example-header-row"></mat-h​​eader-row><mat-row class="example-row" *matRowDef="let row; columns:displayedColumns;"></mat-row></mat-table>

I'm having trouble with importing matSort into my matTable.

I'm providing you with my code:

dashboard.component.ts

import {Component, ViewChild} from '@angular/core';
import {UserService} from "../user.service";
import {DohvatMantisaService} from "../dohvat-mantisa.service";
import {Mantisi} from "../Mantisi";
import {Observable} from "rxjs/Observable";
import {DataSource} from "@angular/cdk/collections";
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import {MatSort} from '@angular/material';
@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent{
  displayedColumns = ['projekt', 'manits', 'kategorija','ozbiljnost','datum_prijave','postavio','odjel','postavio','naziv','status','planirana_isporuka'];
  constructor(private user:UserService, private dohvatMantisa:DohvatMantisaService) {
  }
  dataSource: TableDataSource | null;
  mantisi: Mantisi[];
  name = this.user.getUsername();
  @ViewChild(MatSort) sort: MatSort;
  ngOnInit() {
    this.dataSource = new TableDataSource(this.dohvatMantisa,this.sort);
  }
}

export class TableDataSource extends DataSource<Mantisi>{
  constructor(private mantisiDS: DohvatMantisaService,private sort: MatSort){
    super();
  }
  connect(): Observable<Mantisi[]> {
    const displayDataChanges = [
      this.mantisiDS.dohvatiMantise(),
      this.sort.sortChange,
    ];

    return Observable.merge(...displayDataChanges).map(() => {
      return this.getSortedData();
    });
  }
  disconnect() {}

  getSortedData(): Mantisi[]{
    const data = this.mantisiDS.prikazMantisa().slice();
    if (!this.sort.active || this.sort.direction == '') { return data; }
    return data.sort((a, b) => {
      let propertyA: number|string = '';
      let propertyB: number|string = '';
      switch (this.sort.active) {
        case 'projekt': [propertyA, propertyB] = [a.projekt, b.projekt]; break;
        case 'manits': [propertyA, propertyB] = [a.manits, b.manits]; break;
        case 'kategorija': [propertyA, propertyB] = [a.kategorija, b.kategorija]; break;
        case 'ozbiljnost': [propertyA, propertyB] = [a.ozbiljnost, b.ozbiljnost]; break;
        case 'datum_prijave': [propertyA, propertyB] = [a.datum_prijave, b.datum_prijave]; break;
        case 'postavio': [propertyA, propertyB] = [a.postavio, b.postavio]; break;
        case 'naziv': [propertyA, propertyB] = [a.naziv, b.naziv]; break;
        case 'status': [propertyA, propertyB] = [a.status, b.status]; break;
        case 'planirana_isporuka': [propertyA, propertyB] = [a.planirana_isporuka, b.planirana_isporuka]; break;
      }

      let valueA = isNaN(+propertyA) ? propertyA : +propertyA;
      let valueB = isNaN(+propertyB) ? propertyB : +propertyB;

      return (valueA < valueB ? -1 : 1) * (this.sort.direction == 'asc' ? 1 : -1);
    });
  }
}

This is my service: dohvatMantisaService

import { Injectable } from '@angular/core';
import {Http, Response, RequestOptions, Headers} from "@angular/http";
import {Observable} from "rxjs/Observable";
import {Mantisi} from "./Mantisi";
import 'rxjs';
import 'rxjs/operator/map';
import 'rxjs/operator/do';

@Injectable()
export class DohvatMantisaService {
  constructor(public http:Http) { }
  result: Mantisi[];
  dohvatiMantise(): Observable<Mantisi[]>{
    return this.http.get('/mantis/getMantisReport').map(this.extractData);
  }
  private extractData(response: Response) {
    let body = response.json();
    return body || {};
  }

  prikazMantisa(): Mantisi[]{
    this.dohvatiMantise().subscribe(res => this.result = res);
    return this.result;
  }
}

And im providing you with my dashboard.component.html matSort row:

<mat-table #table [dataSource]="dataSource" class="example-table" matSort>

The main problem here is that data is loaded and acquired from http request but I'm getting errors in console something like this:

Cannot read property 'sortChange' of undefined at TableDataSource.webpackJsonp.../../../../../src/app/dashboard/dashboard.component.ts.TableDataSource.connect (dashboard.component.ts:36) at MatTable.webpackJsonp.../../../cdk/esm5/table.es5.js.CdkTable._observeRenderChanges (table.es5.js:602) at MatTable.webpackJsonp.../../../cdk/esm5/table.es5.js.CdkTable.ngAfterContentChecked (table.es5.js:522)

It tells me that this.sort.sortChange is undefined. I searched all bit of internet and couldn't find proper answer. Hope you can help me with that.

解决方案

I've found solution for this problem.

The main problem was that table was rendered before data arrived. I've loaded data first and sent it like source to dataSource constructor. After it, problem disappeared. That's the thing with async http.get and services.

Thanks for you help.

fetchData(id){
  this.fetch.getProcesses(id).subscribe(result => {
    this.processes = result;
    this.dataSource = new TableDataSource(this.processes);
    Observable.fromEvent(this.filter.nativeElement, 'keyup')
      .debounceTime(150)
      .distinctUntilChanged()
      .subscribe(() => {
        if (!this.dataSource) {
          return;
        }
        this.dataSource.filter = this.filter.nativeElement.value;
      });
  });
}




export class TableDataSource extends DataSource<Proces>{
  _filterChange = new BehaviorSubject('');
  get filter(): string {
    return this._filterChange.value;
  }
  set filter(filter: string) {
    this._filterChange.next(filter);
  }
  filteredData: any =[];

  constructor(private processes:Proces[]){
    super();
  }
  connect(): Observable<Proces[]>{
    const displayDataChanges = [
      this.processes,
      this._filterChange,
    ];
    return Observable.merge(...displayDataChanges).map(() => {
      this.filteredData = this.processes.slice().filter((item: Proces) => {
        const searchStr = (item.name).toLowerCase();
        return searchStr.indexOf(this.filter.toLowerCase()) !== -1;

      });
      return this.filteredData;
    })
  }
  disconnect(){}
}



      <div class="header">
    <mat-form-field floatPlaceholder="never">
      <input matInput #filter placeholder="Pretraži procese">
    </mat-form-field>
  </div>
  <mat-table #table [dataSource]="dataSource" class="table-mantis" matSort>

    <ng-container matColumnDef="col1">
      <mat-header-cell *matHeaderCellDef class="table-header-cell" mat-sort-header> Name</mat-header-cell>
      <mat-cell *matCellDef="let row" class="example-cell" > {{row.nazivProcesa}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="col2">
      <mat-header-cell *matHeaderCellDef class="table-header-cell" mat-sort-header> Cell 2</mat-header-cell>
      <mat-cell *matCellDef="let row" class="example-cell" > {{row.nazivVlasnika
        }} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="col3">
      <mat-header-cell *matHeaderCellDef class="table-header-cell" mat-sort-header> Cell 3</mat-header-cell>
      <mat-cell *matCellDef="let row" class="example-cell" > {{row.interniAkt}} </mat-cell>
    </ng-container>

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

这篇关于Angular matSort 不排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆