это интерфейс Tickets[]
export interface Tickets {
name: string;
id: number;
}
это сервис, который я создал, который должен возвращать данные, извлеченные из API ... но здесь я жестко закодировал данные (пожалуйста, кто-то должен помочь мне с правильной функцией возвращает данные из api
в функции getData()
)
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Tickets } from './ticket.model'
@Injectable({
providedIn: 'root'
})
export class OpenTicketsService {
private _url:string = 'assets/data.json';
constructor(private http: HttpClient) { }
dataRequest():Observable<Tickets[]>{
return this.http.get<Tickets[]>(this._url);
}
getData(){
//to be replace with the code that will subscribe to `dataRequest()` and return the data
return [
{id: 1, name: 'Hydrogen'},
{id: 2, name: 'Helium'},
{id: 3, name: 'Lithium'},
{id: 4, name: 'Beryllium'},
{id: 5, name: 'Boron'},
{id: 6, name: 'Carbon'},
{id: 7, name: 'Nitrogen'},
{id: 8, name: 'Oxygen'},
{id: 9, name: 'Fluorine'},
{id: 10, name: 'Neon'},
];
}
это файл datasource.ts, сгенерированный вместе с angular таблицей данных материала
import { DataSource } from '@angular/cdk/collections';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';
import { OpenTicketsService } from './open-tickets.service';
import { Tickets } from './ticket.model';
export class TicketsTableDataSource extends DataSource<Tickets> {
//this is the function that will return the data from OpenTicketsService and assign it to "data"
data: Tickets[] = this.ticketService.getData();
paginator: MatPaginator;
sort: MatSort;
constructor(private ticketService:OpenTicketsService) {
super();
}
connect(): Observable<Tickets[]> {
const dataMutations = [
observableOf(this.data),
this.paginator.page,
this.sort.sortChange
];
return merge(...dataMutations).pipe(map(() => {
return this.getPagedData(this.getSortedData([...this.data]));
}));
}
disconnect() {}
private getPagedData(data: Tickets[]) {
const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
return data.splice(startIndex, this.paginator.pageSize);
}
private getSortedData(data: Tickets[]) {
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);
case 'id': return compare(+a.id, +b.id, isAsc);
default: return 0;
}
});
}
}
function compare(a: string | number, b: string | number, isAsc: boolean) {
return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
Файл .ts, который будет отображать данные о компоненте. html
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTable } from '@angular/material/table';
import { TicketsTableDataSource } from './tickets-table-datasource';
import { Tickets } from './ticket.model';
import { OpenTicketsService } from './open-tickets.service';
@Component({
selector: 'app-tickets-table',
templateUrl: './tickets-table.component.html',
styleUrls: ['./tickets-table.component.scss']
})
export class TicketsTableComponent implements AfterViewInit, OnInit {
constructor(private ticketService:OpenTicketsService) { }
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
@ViewChild(MatTable) table: MatTable<Tickets>;
dataSource: TicketsTableDataSource;
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns = ['id', 'name'];
ngOnInit() {
this.dataSource = new TicketsTableDataSource(this.ticketService);
}
ngAfterViewInit() {
this.dataSource.sort = this.sort;
this.dataSource.paginator = this.paginator;
this.table.dataSource = this.dataSource;
}
}