我有这个 Material 表,它通过 Rest API 显示来自 JSON url 的数据。我现在想在材料表上使用 sort\pagination 但无法通过它。下面是截图。我如何同时提及MatTableDataSource
两者UserDataSource
?我想坚持使用Observable
. 请告知,我是 Angular 的新手。
组件.ts
@Component({
selector: 'app-tablefilter',
templateUrl: './tablefilter.component.html',
styleUrls: ['./tablefilter.component.scss']
})
export class TablefilterComponent implements OnInit {
@ViewChild(MatSort, {static: true}) sort: MatSort;
displayedColumns: string[] = ['name','email','phone','website', 'address'];
dataSource = new UserDataSource(this.dataService );
constructor(private dataService: DataService) {}
ngOnInit() {
}
}
export class UserDataSource extends DataSource<any> {
constructor(private dataService: DataService) {
super();
}
connect(): Observable<Contacts[]> {
return this.dataService.fetchPosts();
}
disconnect() {}
}
HTML
<table mat-table matSort class="mat-elevation-z8" [dataSource]="dataSource">
<ng-container matColumnDef="phone">
<th mat-header-cell *matHeaderCellDef mat-sort-header> phone
</th>
<td mat-cell *matCellDef="let contacts">{{contacts.phone}} </td>
</ng-container>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header> name </th>
<td mat-cell *matCellDef="let contacts"> {{contacts.name}} </td>
</ng-container>
<ng-container matColumnDef="email">
<th mat-header-cell *matHeaderCellDef> email </th>
<td mat-cell *matCellDef="let contacts"> {{contacts.email}} </td>
</ng-container>
<ng-container matColumnDef="website">
<th mat-header-cell *matHeaderCellDef> website </th>
<td mat-cell *matCellDef="let contacts"> {{contacts.website}} </td>
</ng-container>
<ng-container matColumnDef="address">
<th mat-header-cell *matHeaderCellDef> address </th>
<td mat-cell *matCellDef="let contacts"> {{contacts.address.street}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
服务-data.service.ts
import { Injectable } from '@angular/core';
import{ Observable } from 'rxjs/observable';
import { HttpClient } from '@angular/common/http';
import {Contacts} from '../models/contacts.model';
import { map, tap } from 'rxjs/operators';
import 'rxjs/add/operator/map';
@Injectable({
providedIn: 'root'
})
export class DataService {
private serviceUrl = 'https://jsonplaceholder.typicode.com/users';
constructor( private http: HttpClient ) { }
fetchPosts(): Observable<Contacts[]> {
return this.http.get<Contacts[]>(this.serviceUrl )
}
}