Vincent Chen
Vincent Chen

Reputation: 265

angular7 ag-grid this.http is undefined error

I tried to use ag-grid in angular7, my code looks like below:


    import { Component, OnInit } from '@angular/core';
    import { HttpClient, HttpHeaders } from '@angular/common/http';

    import { AgGridModule} from 'ag-grid-angular';

    @Component({
      selector: 'app-top100sp',
      templateUrl: './top100sp.component.html',
      styleUrls: ['./top100sp.component.css']
    })
    export class Top100spComponent implements OnInit {


      private top100url = 'http://resturl';

      private gridOptions;
      private row_per_page = 20;

      private endpoint;
      private rowData;
      private restDatasource;

      private columnDefs = [
        .
        .
        .
      ];

      constructor(private http: HttpClient) { }

      ngOnInit() {
          this.gridOptions = {
              columnDefs: this.columnDefs,
              rowModelType: 'infinite',
              //datasource: this.restDatasource,
              enableServerSideFilter: false,
              enableServerSideSorting: false,
              pagination: true, 
              paginationPageSize: this.row_per_page
         };
      }

      gridReady($event) {
          console.log("onGridReady "+$event.api.paginationGetPageSize());
          this.restDatasource = {
              rowCount: null,
              getRows: function(params) {
                  console.log(params.startRow + " to " + params.endRow);
                  this.endpoint = this.top100url + "/"+ params.startRow +"/" + params.endRow;
                  this.http.get(this.endpoint).subscribe((results) => {
                      //console.log(results);
                      //this.rowData = results;
                        params.successCallback(results, 20);
                  });
              }   
          };  
          $event.api.setDatasource(this.restDatasource);
      };

    }

When page initialized, I got the following error in javascript console.

ERROR TypeError: "this.http is undefined"

Why this.http is undefined? I inject it through constructor.

I have expreience with Angular UI Grid, is there similar solution for angular 7?

Upvotes: 5

Views: 1091

Answers (1)

Paritosh
Paritosh

Reputation: 11560

Use arrow function to define getRows method.

getRows = (params) => {
     console.log(params.startRow + " to " + params.endRow);
     this.endpoint = this.top100url + "/"+ params.startRow +"/" + params.endRow;

     this.http.get(this.endpoint).subscribe((results) => {
        //console.log(results);
        //this.rowData = results;
        params.successCallback(results, 20);
     });
 }   

Upvotes: 4

Related Questions