注入服务中的Angular 2未定义

时间:2017-01-26 15:03:19

标签: angular angular2-injection

我有一个Angular 2组件,它实现了一个接口IDatasource作为AG-GRID的一部分

我无法从dataSource getRows函数中获取注入的httpClient服务。

我认为这与注射有关,我只是不理解;但我无法理解为什么。

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

还尝试将其定义为单独的属性并得到完全相同的问题。

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

1 个答案:

答案 0 :(得分:2)

如果您想使用'this inside the callback use()=&gt; instead of函数()`

getRows: function (params) {

应该是

getRows: (params) => {