Dave
Dave

Reputation: 19090

How do I automatically refresh my PrimeNG table from data from my ngrx/data service?

I'm using Angular 13 and ngrx/data, store and entity (v.13). I have set up my ngrx/data service

export class MyObjService extends DefaultDataService<MyObject> {
    ...
}

and then a component using PrimeNg. I have a table to display all my objects ...

<p-table #dt [value]="(myObjects$ | async)!" ...

In which the service file contains

  constructor(
    ...
    private service: MyObjService,
  ) { 
      ...
      this.myObjects$ = this.service.getAll(); 

The issue is every time I do an operation that alters the backend store, for example a delete

  del(id: number){
    this.myObjService.delete(id)
    .subscribe(_ => {
      this.MyObjects$ = this.myObjService.getAll();
    } );

I have to refresh the table (I have to call "this.myObjects$ = this.myObjService.getAll();" above). Is there a way I can set the table so that the data in the table refreshes automatically? I feel like this is something ngrx/data would allow me to do but not sure how it is done.

Upvotes: 2

Views: 1691

Answers (1)

debugger
debugger

Reputation: 1727

First you can add a method to your service for listening an event: let's assume you have an object which contains your table data. let's say Category is an object with id,name and all data fields. Then you can import Subject from rxjs which is an observable. in your service.ts file :

 export class CategoriesService {
  private categories:Category[] = [];
  private categoryUpdated = new Subject<Category[]>();

then you can add a method as middleware:

 getUpdateListener(){
    return this.categoryUpdated.asObservable();
  }

then go to your category.ts file : import Subscription from rxjs and store it in a variable.

export class CategoriesComponent implements OnInit{
categories : Category[] = [];
category : Category; 
private categorySub : Subscription;

then the constructor :

constructor(private _categoriesService : CategoriesService){}

in ngOnInit first we get the Category from the service file. Like you are getting the datas. Then we execute our observation in subscription.And we set the object value through it.

ngOnInit(){
    this._categoriesService.getCategories();
    this.categorySub = this._categoriesService.getUpdateListener().subscribe((cate: Category[])=>{
      this.categories = cate;
    }) 
  }

then you don't need to use other observable anymore it will handle everything.

Upvotes: 1

Related Questions