2

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?

Dandesaj
  • 107
  • 8

1 Answers1

1

I have tested this and it wors for me :)

You have to add the following steps:

In your app.module.ts

  1. Add this import
import { Injector, NgModule } from '@angular/core';
  1. Export the injector
export let AppInjector: Injector;
  1. Initialize it in the AppModule constructor:
export class AppModule {
  constructor(private injector: Injector) {
    AppInjector = this.injector;
  }
}

In your datasource.ts

  1. Import AppInjector
import { AppInjector } from '../../app.module';
  1. Initialize it in your constructor
constructor() {
    const myService = AppInjector.get(ApiService);
  }

I hope I've helped you

  • It seems to be working but I'm unable to confirm 100% as I'm having issues elsewhere with my code. Once I get that sorted I'll be able to accept the answer with more certainty – Dandesaj Mar 21 '22 at 14:45
  • This issues im having at the moment are that although the data is loading from the datasource file this isnt displayed immediately, i have to sort one of the columns for this to become visible – Dandesaj Mar 25 '22 at 16:00
  • This example is very minimalistic, though it may solve the problem for someone proficient at angular it is still unclear for intermediate beginners. Do you have more detailed version of this example – alpha027 Jan 29 '23 at 12:23