I'm working with Angular-NGRX and i have 3 components that can modify the data of a list. In the main component I listen for all the changes to update the listing and it works. The problem is that the first load subscribes me 3 times.

This is the ngOnInit of the main component:

  ngOnInit(): void {
    // Change order
    this.store.select(state => state.shared.orderBy).pipe(
      takeUntil(this.onDestroy$),
      tap(resp => {
        this.orderBy = resp;
        this._cmsFunctions.deselectAll('Resource');
      }),
      switchMap(resp => this._dynamicComponentsService.loadResources(this.itemsToShow, this.tabCounter, this.orderBy, this.filters, this.searchTerm, this.company, this.workgroup, (this.paramCode) ? this.paramCode : 0))
      ).subscribe();

    // Change filters
    this.store.select(state => state.shared.filters).pipe(
      takeUntil(this.onDestroy$),
      tap(resp => {
        this.filters = resp;
        this._cmsFunctions.deselectAll('Resource');
      }),
      switchMap(resp => this._dynamicComponentsService.loadResources(this.itemsToShow, this.tabCounter, this.orderBy, this.filters, this.searchTerm, this.company, this.workgroup, (this.paramCode) ? this.paramCode : 0))
      ).subscribe();

    // Change search term
    this.store.select(state => state.shared.searchTerm).pipe(
      takeUntil(this.onDestroy$),
      tap(resp => {
        this.searchTerm = resp;
        this._cmsFunctions.deselectAll('Resource');
      }),
      switchMap(resp => this._dynamicComponentsService.loadResources(this.itemsToShow, this.tabCounter, this.orderBy, this.filters, this.searchTerm, this.company, this.workgroup, (this.paramCode) ? this.paramCode : 0))
      ).subscribe();
  }

And all i need is that when starting it only subscribes once:

enter image description here

How can I improve this code?

Thanks!

1

There are 1 best solutions below

0
On

You shouldn't be making calls to a data service from the component, and certainly not based on selector calls. You should be dispatching an Action which is captured and handled by an Effect. You can use dataLoading and dataLoaded flags in your store, for example, to prevent multiple loads.