Generating a table using the angular material schematics presents you with a table component that include a datasource.ts file. In this, the data to be displayed is hard coded.
I have replaced the interface in this file to match my data, and with the use of my imported ApiService I can pull data from my api.
datasource.ts
export interface TestTableItem {
CompanyName: string;
Sites: number;
BaseUnits: number;
Sensors: number;
}
export class TestTableDataSource extends DataSource<TestTableItem> {
data: TestTableItem[] = [];
paginator: MatPaginator | undefined;
sort: MatSort | undefined;
constructor(private service: ApiService) {
super();
this.service.getCompanies().subscribe((response) => {
this.data = response;
});
}
The issue I'm having is in my component.ts file. When constructing the datasource class, this expects an argument
component.ts
constructor() {
this.dataSource = new TestTableDataSource();
}
Expected 1 arguments, but got 0. An argument for 'service' was not provided.
How can I make sure the apiservice is accessible by the datasource and not requiere it as an argument?
I have tested this and it wors for me :)
You have to add the following steps:
In your app.module.ts
import { Injector, NgModule } from '@angular/core';
export let AppInjector: Injector;
export class AppModule {
constructor(private injector: Injector) {
AppInjector = this.injector;
}
}
In your datasource.ts
import { AppInjector } from '../../app.module';
constructor() {
const myService = AppInjector.get(ApiService);
}
I hope I've helped you