Search code examples
angularhttpclientangular5angular-http-interceptors

How to cancel HttpRequests when changing a component


I'm developping an application with angular 5.

I need to stop all http queries when changing/detroyiog components.

example : i open ListUsersComponent, a httpquery is started to get the list of users, before that query is finished i opened ListAdminsComponent. so in network (browser) i have the query getting the list of users query still pending.

I want to stop it when i destroy ListUsersComponent.

how stop queries when i change the component?


Solution

  • this is the solution :

    @Injectable()
    export class HttpCancelInterceptor implements HttpInterceptor {
      constructor(private httpCancelService: HttpCancelService) { }
    
      intercept<T>(req: HttpRequest<T>, next: HttpHandler): Observable<HttpEvent<T>> {
        return next.handle(req).takeUntil(this.httpCancelService.onCancelPendingRequests())
      }
    }
    

    CancelService

    @Injectable()
    export class HttpCancelService {
      private cancelPendingRequests$ = new Subject<void>()
    
      constructor() { }
    
      /** Cancels all pending Http requests. */
      public cancelPendingRequests() {
        this.cancelPendingRequests$.next()
      }
    
      public onCancelPendingRequests() {
        return this.cancelPendingRequests$.asObservable()
      }
    
    }
    

    link : cancel