NGXS Actions are dispatched again when path is updated

79 Views Asked by At

I have a problem with NGXS Actions. All actions are dispatched(or handled) again when path is updated via Angular router.

I noticed that this happens when a path is changed eg. /news/today -> /news/labels/1. This do not happen when only param's value is changed.

I will appreciate any advice regarding what can I check, or how can I debug this

App workflow:

  1. when button is clicked then url path is updated
 this.router.navigate([uri], extras);
  1. there is a central component which dispatch NGXS Action when path is updated
combineLatest([cfg$, url$, urlParams$, queryParams$])
  .pipe(
     filter((vals) => vals.every(isNotNull)),
     map(([cfg, url, urlParams, queryParams]) =>
     this.createRequest(cfg!, url, urlParams, queryParams)
  )
)
  .subscribe((request) => this.store.dispatch(new GetNewsPosts(request)));
  1. Data is loaded via Http Get
  @Action(GetNewsPosts)
  getNewsPosts(ctx: StateContext<NewsItemsModel>, { request }: GetNewsPosts) {
    console.log('GetNewsPosts', request);
    ctx.setState({ loadingFirstPage: true, pages: [], request });

    const response$ = this.service.getPosts(0, request); 
    return handleGetFirstPageResponse(ctx, dataName, response$); // returns Observable
  }

Versions:

  • Angular 15.1.5
  • @ngxs/store: 3.8.1
1

There are 1 best solutions below

0
On

There was a problem with my code, the event was triggered, which dispatch a new value of cfg$, every time a path was updated

adding debounceTime helped me to find this out

combineLatest([cfg$, url$, urlParams$, queryParams$])
      .pipe(
        filter((vals) => vals.every(isNotNull)),
        debounceTime(30),
        map(([cfg, url, urlParams, queryParams]) =>
          this.createRequest(cfg!, url, urlParams, queryParams)
        )
      )
      .subscribe((request) => this.store.dispatch(new GetNewsPosts(request)));