angularangular2-injection

Angular 2 Undefined on Injected Service


I've got an Angular 2 Component which implements an interface IDatasource as part of AG-GRID

I cannot get the injected httpClient Service to be available from within the dataSource getRows function.

I'm assuming this is something to do with the injection which I'm just not understanding; but I can't wrap my head around why.

constructor(private httpClient: HttpClient) {
    //This one works perfectly fine and httpClient is defined.
    console.log(this.httpClient);

    this.gridOptions = <GridOptions>{
        //Removed other config for brevity.
        datasource: {
            getRows: function (params) {
                let data: any[] = [];


                //this one - the httpClient is undefined. No idea why?
                console.log(this.httpClient);


                // this.httpClient.post('incidents/GetIncidentList', params).subscribe(response => data = response.json());
                let lastRow = -1;
                params.successCallback(data, lastRow);
            }
        }
    };
}

Also tried defining it as a seperate property and got the exact same issue.

private dataSource: IDatasource = {
    getRows: function (params) {
        let data: any[] = [];
        console.log(this.httpClient);
        // this.httpClient.post('incidents/GetIncidentList', params).subscribe(response => data = response.json());
        let lastRow = -1;
        params.successCallback(data, lastRow);
    }
}

Solution

  • If you want to use ´thisinside the callback use() =>instead offunction()`

    getRows: function (params) {
    

    should be

    getRows: (params) => {