0

I've been trying to think of a good way to cancel previous HTTP request when new requests are fired, for which I would normally use the switchMap operator. However, due to my request being not bound to a button click or any other event, but is instead proxied to the NGXS store in an action dispatch, I can't really think of how I would do that.

Consider the following setup:

In the app.component.ts, you'd have something like:

@Component({
  selector: 'app-component',
  template: '<div (click)="sendRequestForData()">Click me!</div>'
})
export class AppComponent {
  //...some selectors

  constructor(private store: Store) {}

  sendRequestForData() {
    this.store.dispatch(new Fetch());
  }
  //...
}

Further, there would be an action in store set up something like this:

@Action(Fetch)
private fetchFromDatabase(ctx: StateContext<StateModel>) {
   this.http.get('url').pipe(
     catchError(err => {
       ctx.dispatch(new FetchError());
       return of(false);
     }),
     tap(data => {
        if(typeof data !== 'boolean') {
          ctx.dispatch(new FetchSuccess());
        }
     })).subscribe();
   )

This setup in the fetching action has not source observable (as in something acting like the button click observable) to really "switch" from in order to even use a switchMap, so how would I use a switchMap in this setup?

  • 2
    Try returning the observable instead of subscribing inside the `Action()` and use [`@Action(Fetch, { cancelUncompleted: true })`](https://www.ngxs.io/advanced/cancellation#basic). – ruth Jul 27 '23 at 15:26
  • Didn't even know that was a thing, that's amazing, thank you so much :) – Heribert Greinix Jul 31 '23 at 08:10

0 Answers0