0

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?

sebu
  • 2,824
  • 1
  • 30
  • 45
walidtlili
  • 840
  • 2
  • 13
  • 36

1 Answers1

0

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

walidtlili
  • 840
  • 2
  • 13
  • 36