Search code examples
angularangular-materialangular-material-table

How to properly set up angular table datasource to pull data from API


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?


Solution

  • 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