Я создал таблицу, используя команду ng generate @ angular / material: material-table, используя угловой интерфейс командной строки.
Мне удалось получить данные макета из моего https://jsonplaceholder.typicode.com/users, используя данные-Функция service.ts getUser (), которую я создал.
проблема в том, что данные не отображаются в таблице при инициализации, а отображаются, когда я нажимаю кнопку перехода на следующую страницу (нумерацию страниц) или кнопку сортировки.
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");
}
}
iбуду признателен за вашу помощь.Также это мой первый вопрос, поэтому, пожалуйста, не обращайте на меня слишком много внимания:)