typescriptangular8ngrx-storengrx-effectsrxjs-observables

How cancel angular http request made in RXJS Effects


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 angular components will be invoking this action with a different payload.


Solution

  • 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);
        }));
    
    }));