1

From my Angular code, I'm calling a synchronous method where there is an asynchronous call to a service(myService) which sets the value of a variable(myVariable) inside it. This variable myVariable in turn is bound with a p-datatable object like so:

<p-dataTable [value]="someValue" [(selection)]="myVariable" [paginator]="true" #MyTable ...>

During the initial page load, the correct values get displayed in the data table. But when there is a change in the data that is returned by the service, it fails to bind to the latest value of the variable without an explicit refresh.

My code snippet:

ngOnInit(){
  this.getData(par1, par2);
  // other lines of code
  // ........
}

myMethod(){
   this.getData(par1, par2); // this method call is expected to update the value of the variable
   // other lines of code
   // ........
}

getData(p1, p2){
 this.myService.getDataFromServer(p1, p2)
   .subscribe(data => {
       myVariable = data.value;
       // other lines of code
       // ........
    });
}

I understand the fact that myMethod() is receiving data asynchronously, so maybe the variable is not getting set that's why. I tried to directly subscribe to myService.getDataFromServer instead from myMethod() but that doesn't work either. Where am I going wrong here?

The Inquisitive Coder
  • 1,085
  • 3
  • 20
  • 43

1 Answers1

0

Resetting the variable(which binds to the datatable) before fetching updated data from the service fixed the issue for me. Code snippet:

getData(p1, p2){
 this.myService.getDataFromServer(p1, p2)
   .subscribe(data => {
       myVariable = []; // reset done here
       myVariable = data.value;
       // other lines of code
       // ........
    });
}
The Inquisitive Coder
  • 1,085
  • 3
  • 20
  • 43