簡體   English   中英

角材料表:直到單擊分頁器或進行排序,動態數據才會顯示

[英]Angular Material Table: Dynamic data does not show until i click the paginator or sort

我使用Angular CLI使用ng generate @ angular / material:material-table命令創建了一個表。

我已經使用創建的data-service.ts getUser()函數設法從https://jsonplaceholder.typicode.com/users中檢索了模擬數據。

問題是init上的表上沒有顯示數據,但是每當我單擊下一頁(分頁)按鈕或排序按鈕時它就會顯示。

scheduletable-datasource.ts:

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';
import { DataService } from '../data.service'

// TODO: Replace this with your own data model type
export interface ScheduletableItem {
  name: string;
    email: string;
    phone: string;
}


// TODO: replace this with real data from your application
const EXAMPLE_DATA: ScheduletableItem[] = []
/**
 * Data source for the Scheduletable view. This class should
 * encapsulate all logic for fetching and manipulating the displayed data
 * (including sorting, pagination, and filtering).
 */
export class ScheduletableDataSource extends DataSource<ScheduletableItem> {
  data: ScheduletableItem[] = EXAMPLE_DATA;



  constructor(private paginator: MatPaginator, private sort: MatSort, private ds:DataService) {
    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<ScheduletableItem[]> {
    this.ds.getUser().subscribe((res)=>{
      console.log(res);
      this.data = res;
    });
    // 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: ScheduletableItem[]) {
    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: ScheduletableItem[]) {
    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);
        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);
}

scheduletable-component.ts:

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, MatSort } from '@angular/material';
import { ScheduletableDataSource } from './scheduletable-datasource';
import { DataService } from '../data.service';

@Component({
  selector: 'app-scheduletable',
  templateUrl: './scheduletable.component.html',
  styleUrls: ['./scheduletable.component.css'],
})
export class ScheduletableComponent implements OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  dataSource: ScheduletableDataSource;
  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['name', 'email', 'phone'];

  constructor(private ds: DataService){}

  ngOnInit() {
    this.dataSource = new ScheduletableDataSource(this.paginator, this.sort, this.ds);
    console.log(this.dataSource)
  }
}

data.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { ScheduletableItem } from '../app/scheduletable/scheduletable-datasource';
import { from } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  apiLink: string = "http://localhost/apibus/";
  private serviceUrl = 'https://jsonplaceholder.typicode.com/users';

  constructor(private http: HttpClient) { }

  getUser(): Observable<ScheduletableItem[]> {
    console.log(this.http.get<ScheduletableItem[]>(this.serviceUrl));
    return this.http.get<ScheduletableItem[]>(this.serviceUrl);
  }

   pull(method){
    return this.http.get(this.apiLink+method+".php");
  }

}

我將感謝您的幫助。 這也是我的第一個問題,所以請不要對我太刻苦:)

我已經解決了,如果有人遇到相同的確切問題,以下是解決方案:

scheduletable-datasource.ts:

我剛剛轉移了代碼:

this.ds.getUser().subscribe((res)=>{
      console.log(res);
      this.data = res;
    });

在構造函數代碼下,因此您的scheduletable-datasource.ts應該如下所示:

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';
import { DataService } from '../data.service'

export interface ScheduletableItem {
  name: string;
    email: string;
    phone: string;
}





export class ScheduletableDataSource extends DataSource<ScheduletableItem> {
  data: ScheduletableItem[]



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

//FROM connect() to here:

    this.ds.getUser().subscribe((res)=>{
      console.log(res);
      this.data = res;
    });
  }

  connect(): Observable<ScheduletableItem[]> {

    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];


    this.paginator.length = this.data.length;

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

  disconnect() {}

  private getPagedData(data: ScheduletableItem[]) {
    const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
    return data.splice(startIndex, this.paginator.pageSize);
  }

  private getSortedData(data: ScheduletableItem[]) {
    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);
        default: return 0;
      }
    });
  }
}


function compare(a, b, isAsc) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM