Issue
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
- Add this import
import { Injector, NgModule } from '@angular/core';
- Export the injector
export let AppInjector: Injector;
- Initialize it in the AppModule constructor:
export class AppModule {
  constructor(private injector: Injector) {
    AppInjector = this.injector;
  }
}
In your datasource.ts
- Import AppInjector
import { AppInjector } from '../../app.module';
- Initialize it in your constructor
constructor() {
    const myService = AppInjector.get(ApiService);
  }
I hope I've helped you
Answered By - Zaquiel Rodriguez Arce
 
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.