我正在为一个项目尝试使用 Angular,但我一直在为我的 MatTable 创建一个数据源。
我正在使用的 API 发送如下响应:
{
data: [], //array of objects for samples
total: 100, //total number of samples found
pageSize: 10,
pageIndex: 0
}
我的样本模型是:
//Model for a single sample
export class Sample {
id: number;
name: string;
}
//a plural namespace is used for multiple samples returned from API
export class Samples {
samples: Sample[],
total: number;
pageSize: number;
pageIndex: number;
}
// a const in case no samples were found
export const NO_SAMPLES {
total: 0,
pageIndex: 0,
pageSize: 0,
samples: []
}
现在,当我尝试将其与如下数据源集成时:
... //required imports
export class SamplesDataSource extends DataSource<Samples> {
private samplesSubject = new BehaviorSubject<Samples>(NO_SAMPLES);
public constructor(private samplesService: SamplesService) {
super();
}
//this is where the error (described below) is showing
connect(collectionViewer: CollectionViewer): Observable<Samples> {
return this.samplesSubject.asObservable();
}
disconnect(collectionViewer: CollectionViewer): void {
this.samplesSubject.complete();
}
getSamples() {
this.samplesService.getSamples().pipe(
catchError(err => {
return of([]);
})
).subscribe(
samples => this.samplesSubject.next(samples)
);
}
}
但它向我显示错误消息:
src/app/shared/data-sources/samples-data-source.ts(20,5) 中的错误:错误 TS2416:“SamplesDataSource”类型中的属性“连接”不可分配给基本类型“数据源”中的相同属性
我该如何处理这种情况。
请注意,我需要保留total,pageSize并pageIndex让我的分页器与后端的分页器保持一致。
提前致谢。
编辑
应用组件.ts
... //required imports
export class AlertCasesComponent implements OnInit {
...
samplesTableColumns: string[] = ['sampleId', 'sample'];
samplesTablePageSizes: number[] = [10, 20, 50, 100];
samplesDataSource: SamplesDataSource;
...
constructor(samplesService: SamplesService) {
...
}
ngOnInit(): void {
this.samplesDataSource = new SamplesDataSource(this.samplesService);
this.samplesDataSource.getSamples();
...
}
...
}
应用组件.html
<mat-table class="..." [dataSource]="samplesDataSource.samples">
.... //rows and columns implementations
</mat-table>
<mat-paginator [length]="samplesDataSource.total" pageIndex="0" [pageSize]="samplesDataSource.pageSize" [pageSizeOptions]="samplesTablePageSizes" showFirstLastButtons></mat-paginator>