Kieran
Kieran

Reputation: 69

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);
    }
}

Upvotes: 1

Views: 542

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658037

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

getRows: function (params) {

should be

getRows: (params) => {

Upvotes: 2

Related Questions