简体   繁体   中英

NGRX - How to subscribe to multiple requests that update a list, but prevent it from loading multiple times on the first load?

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM