How to cancel a previous HTTP call using switchMap without a source observable?

104 views Asked by At

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?

0

There are 0 answers