Search code examples
angularag-gridangular-routerag-grid-ng2

Reload data from server angular


I display a table with ag grid. In order to display it I have the onGridReady in the app.component.ts:

  onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;
    this.gridApi.sizeColumnsToFit();
    this.rowData = this.api.getAllExperiments(
      this.route.snapshot.params["browse"]
    );
  }

Then the html to build the table is like this:

  <ag-grid-angular 
    #agGrid 
    id="myGrid" 
    style="width: 100%; height: 500px;" 
    class="ag-theme-balham" 
    [rowData]="rowData | async"
    [enableSorting]="true" 
    [animateRows]="true" 
    [floatingFilter]="true" 
    [enableColResize]="true" 
    [pagination]="true"
    [columnDefs]="columnDefs"
    [sortingOrder]="sortingOrder"
    (rowClicked)='onRowClicked($event)'
    (gridReady)="onGridReady($event)">
  </ag-grid-angular>

This works properly.

As you can see in order to get the data from the server I am calling my service taking in account a parameter in the url address, like this:

this.rowData = this.api.getAllExperiments( this.route.snapshot.params["browse"] );

The parameter can be public or private and the url address is like:

http://localhost:4200/experiments/public

And it is defined in the router like this:

  {
    path: 'experiments/:browse',
    component: ExperimentsListComponent,
    data: { title: 'Experiments List' }
  },

This parameter allows to fetch different experiments from the server according to which button is pressed in the nav-bar.

However, given that, the component is already load, it doesn't refresh the data from the server. How could I make the data refresh ?


Solution

  • I found the answer on GitHub. There is no need to change the components, the router or whatever. The only thing to add is in the ngOnInit() in the app.component.ts

    import { Component, OnInit } from '@angular/core';
    import { Router, NavigationEnd } from '@angular/router';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    
    export class AppComponent implements OnInit{
      constructor(public router: Router,) { }
    
      ngOnInit(){
        this.router.routeReuseStrategy.shouldReuseRoute = function(){
          return false;
      };
    
      this.router.events.subscribe((evt) => {
          if (evt instanceof NavigationEnd) {
              this.router.navigated = false;
              window.scrollTo(0, 0);
          }
      });
    
      }
    }
    

    Answer found on GitHub thanks to mihaicux2.