// http-cancel.service.ts
// use this service as DI in component
import {Subject} from 'rxjs';
import {Injectable} from '@angular/core';
@Injectable()
export class HttpCancelService{
private cancelPendingRequestSubject=new Subject<void>()
cancelPendingRequest$ = this.cancelPendingRequestSubject.asObservable();
cancelPendingRequest(){
this.cancelPendingRequestSubject.next();
}
}
==============================================================
//http-cancel-interceptor.service.ts
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable, takeUntil} from 'rxjs';
import {Injectable} from '@angular/core';
import {HttpCancelService} from './http-cancel.service';
import {tap} from 'rxjs/operators';
@Injectable()
export class CancelInterceptor implements HttpInterceptor{
constructor(private cancelService: HttpCancelService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(takeUntil(this.cancelService.cancelPendingRequest$
.pipe(tap(()=> {throw new Error('Request is canceled')}))));
}
}
==============================================================
// app.module.ts
import {HTTP_INTERCEPTORS} from '@angular/common/http';
...
providers: [
...
{provide: HTTP_INTERCEPTORS, useClass: CancelInterceptor, multi: true}
...
],