3

I want to cancel the http request made in RXJS effects in angular 8.

@Effect() getReport$ = this.action$.pipe(
ofType(ActionTypes.GET_WIDGET),   
map(toPayload),
mergeMap(payload => {
  return this.dashboardService.getReport(payload).pipe(
    map(this.extractData),
    switchMap(result => {
      return observableOf(<ReceivedWidgetAction>{
        type: ActionTypes.RECEIVED_WIDGET,
        payload: result
      });
    }),
    catchError((err: Response | any) => {
      return this.handleReportError(err);
    }));

}));

Please let me know how i can do the same using angular 8. Also please note that I wont be able to use switch map as multiple widgets angular components will be invoking this action with a different payload.

Freestyle09
  • 4,894
  • 8
  • 52
  • 83
Rahul Tokase
  • 1,048
  • 9
  • 25

1 Answers1

8

We can cancel the ongoing request by using takeUnitil operator and creating the new action and dispatching the same action using the store whenever we need to cancel the request.

 @Effect() getReport$ = this.action$.pipe(
ofType(ActionTypes.GET_WIDGET),   
map(toPayload),
mergeMap(payload => {
  return this.dashboardService.getReport(payload).pipe(
    map(this.extractData),
    switchMap(result => {
      return observableOf(<ReceivedWidgetAction>{
        type: ActionTypes.RECEIVED_WIDGET,
        payload: result
      });
    }),
    takeUntil(this.action$.pipe(ofType(DashboardActionTypes.CANCEL_REQUEST))),
    catchError((err: Response | any) => {
      return this.handleReportError(err);
    }));

}));
Rahul Tokase
  • 1,048
  • 9
  • 25
  • 1
    Brilliant solution, I would just put the `takeUntil` operator to the bottom, as linter claims that no operator should be placed after a `takeUntil` – adriancho5692 Nov 02 '21 at 12:35
  • 2
    After cancellation, I can't seem to dispatch `GET_WIDGET` again. The effect isn't invoked anymore. – Ramon de Klein Aug 08 '22 at 14:33