How to cancel/unsubscribe all pending HTTP requests in Angular 4+

AngularTypescriptRxjsAngular Http-Interceptors

Angular Problem Overview


How to cancel/abort all pending HTTP requests in angular 4+.

There is an unsubscribe method to cancel HTTP Requests but how to cancel all pending requests all at once.

Especially while route change.

There is one thing I did

ngOnDestroy() {
  this.subscription.unsubscribe();
}

but how to achieve this globally

Any Ideas?

Angular Solutions


Solution 1 - Angular

Checkout the takeUntil() operator from RxJS to globally drop your subscriptions :

- RxJS 6+ (using the pipe syntax)

import { takeUntil } from 'rxjs/operators';

export class YourComponent {
   protected ngUnsubscribe: Subject<void> = new Subject<void>();

   [...]

   public httpGet(): void {
      this.http.get()
          .pipe( takeUntil(this.ngUnsubscribe) )
          .subscribe( (data) => { ... });
   }

   public ngOnDestroy(): void {
       // This aborts all HTTP requests.
       this.ngUnsubscribe.next();
       // This completes the subject properlly.
       this.ngUnsubscribe.complete();
   }
}

- RxJS < 6

import 'rxjs/add/operator/takeUntil'

export class YourComponent {
   protected ngUnsubscribe: Subject<void> = new Subject<void>();

   [...]

   public httpGet(): void {
      this.http.get()
         .takeUntil(this.ngUnsubscribe)
         .subscribe( (data) => { ... })
   }

   public ngOnDestroy(): void {
       this.ngUnsubscribe.next();
       this.ngUnsubscribe.complete();
   }
}

You can basically emit an event on your unsubscribe Subject using next() everytime you want to complete a bunch of streams. It is also good practice to unsubscribe to active Observables as the component is destroyed, to avoid memory leaks.

Worth reading :

Solution 2 - Angular

You can create an interceptor to apply takeUntil operator to every request. Then on route change you will emit event that will cancel all pending requests.

@Injectable()
export class HttpCancelInterceptor implements HttpInterceptor {
  constructor(private httpCancelService: HttpCancelService) { }

  intercept<T>(req: HttpRequest<T>, next: HttpHandler): Observable<HttpEvent<T>> {
    return next.handle(req).pipe(takeUntil(this.httpCancelService.onCancelPendingRequests()))
  }
}

Helper service.

@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()
  }

}

Hook on route changes somewhere in your app (e.g. onInit in appComponent).

this.router.events.subscribe(event => {
  if (event instanceof ActivationEnd) {
    this.httpCancelService.cancelPendingRequests()
  }
})

And last but not least, register the interceptor to your app.module.ts:

  import { HttpCancelInterceptor } from 'path/to/http-cancel.interceptor';
  import { HTTP_INTERCEPTORS } from '@angular/common/http';
  
  @NgModule({
    [...]
    providers: [
      {
        multi: true,
        provide: HTTP_INTERCEPTORS,
        useClass: HttpCancelInterceptor
      }
    ],
    [...]
  })
  export class AppModule { }

Solution 3 - Angular

If you don't want to manually unsubscribe all subscriptions, then you can do this:

export function AutoUnsubscribe(constructor) {

  const original = constructor.prototype.ngOnDestroy;

  constructor.prototype.ngOnDestroy = function() {
    for (const prop in this) {
      if (prop) {
        const property = this[prop];
        if (property && (typeof property.unsubscribe === 'function')) {
          property.unsubscribe();
        }
      }
    }

    if (original && typeof original === 'function') {
      original.apply(this, arguments)
    };
  };

}

Then you can use it as decorator in your component

@AutoUnsubscribe
export class YourComponent  {
}

but you still need to store subscriptions as component properties. And when you navigating out of component, AutoUnsubscribe function will occurs.

Solution 4 - Angular

I'm not convinced of the need for the functionality requested, but you can accomplish this, cancelling all outstanding requests whenever and wherever you wish by wrapping the framework's http service and delegating to it.

However, when we go about implementing this service, a problem quickly becomes apparent. On the one hand, we would like to avoid changing existing code, including third party code, which leverages the stock Angular http client. On the other hand, we would like to avoid implementation inheritance.

To get the best of both worlds we can implement the Angular Http service with our wrapper. Existing code will continue to work without changes (provided said code does not do anything stupid like use http instanceof Http).

import {Http, Request, RequestOptions, RequestOptionsArgs, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Subscription} from 'rxjs/Subscription';



export default interface CancellationAwareHttpClient extends Http { }

export default class CancellationAwareHttpClient {
  constructor(private wrapped: Http) {
    const delegatedMethods: Array<keyof Http> = [
      'get', 'post', 'put', 'delete',
      'patch', 'head', 'options'
    ];
    for (const key of delegatedMethods) {
      this[key] = wrapped[key].bind(wrapped);
    }
  }

  cancelOutstandingRequests() {
    this.subscriptions.forEach(subscription => {
      subscription.unsubscribe();
    });
    this.subscriptions = [];
  }

  request(url: string | Request, options?: RequestOptionsArgs) {
    const subscription = this.wrapped.request(url, options);
    this.subscriptions.push(subscription);
    return subscription;
  }

  subscriptions: Subscription[] = [];
}

Note that the interface and class declarations for CancellationAwareHttpClient are merged. In this way, our class implements Http by virtue of the interface declaration's extends clause.

Now we will provide our service

import {NgModule} from '@angular/core';
import {ConnectionBackend, RequestOptions} from '@angular/http';

import CancellationAwareHttpClient from 'app/services/cancellation-aware-http-client';

let cancellationAwareClient: CancellationAwareHttpClient;

const httpProvider = {
  provide: Http,
  deps: [ConnectionBackend, RequestOptions],
  useFactory: function (backend: ConnectionBackend, defaultOptions: RequestOptions) {
    if (!cancellationAwareClient) {
      const wrapped = new Http(backend, defaultOptions);
      cancellationAwareClient = new CancellationAwareHttpClient(wrappedHttp);
    }
    return cancellationAwareClient;
  }
};

@NgModule({
  providers: [
    // provide our service as `Http`, replacing the stock provider
    httpProvider,
    // provide the same instance of our service as `CancellationAwareHttpClient`
    // for those wanting access to `cancelOutstandingRequests`
    {...httpProvider, provide: CancellationAwareHttpClient}
  ]
}) export class SomeModule {}

Note how we override the existing framework provided service. We use a factory to create our instance and do not add any decorators for DI to the wrapper itself in order to avoid a cycle in the injector.

Solution 5 - Angular

ngOnDestroy callback is typically used for any custom cleanup that needs to occur when the instance is destroyed.

where do you want to cancel your request?

maybe if you want cancel your requests on browser close there is creative idea here

Solution 6 - Angular

Try This :

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Rx';

export class Component implements OnInit, OnDestroy {
    private subscription: Subscription;
    ngOnInit() {
        this.subscription = this.route.params.subscribe();
    }
    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

Solution 7 - Angular

    //This is the example of cancelling the get request once you leave the TestComponent.
    
    import { Component, OnInit} from '@angular/core';
    
    @Component({
      selector: 'app-test',
      templateUrl: './test.component.html'
    })
    export class TestComponent implements OnInit {
    
      request: any;
someList: any;
    
      constructor( private _someService: SomeService) {
       
      }
    
    ngOnInit() {
        this.getList();
      }
    
      ngOnDestroy(){
        this.request.unsubscribe(); // To cancel the get request.
      }
    
      getList() {
        this.request= this._someService.getAll()
          .subscribe((response: any) => {
            this.someList= response;
          }, (error) => {
            console.log("Error fetching List", error);
          })
      }
    
    }

Solution 8 - Angular

Adding something to @Bladito answer which is almost perfect.

Actually, the HttpCancelService stack is perfect, but the probleme is where it's called. Calling this on navigation end may cause problems if you have child routes.

So I made an abstract container component which call the HttpCancelService when it's destroyed. That way I can manage when I want to cut any Http Cancelling request with more fine grain.

import { Component, OnDestroy, OnInit } from '@angular/core';
import { HttpCancelService } from '../../services/http-cancel-service.service';

@Component({
  selector: 'some-abstract-container',
  template: `
    ABSTRACT COMPONENT
  `,
  styleUrls: ['./abstract-container.component.scss']
})
export class AbstractContainerComponent implements OnInit, OnDestroy {
  constructor(protected readonly httpCancelService: HttpCancelService) {}

  ngOnInit() {}

  ngOnDestroy(): void {
    this.httpCancelService.cancelPendingRequests();
  }
}


And there it's a concrete component extending the abstract component:

import { Component, OnInit } from '@angular/core';
import { AbstractContainerComponent } from '../../../shared/components/abstract-container/abstract-container.component';
import { HttpCancelService } from '../../../shared/services/http-cancel-service.service';

@Component({
  selector: 'some-concrete-container',
  templateUrl: '.some-concrete-container.component.html',
  styleUrls: ['./some-concrete-container.component.scss']
})
export class SomeConcreteContainerComponent extends AbstractContainerComponent implements OnInit {
  constructor(protected readonly httpCancelService: HttpCancelService) {
    super(httpCancelService);
  }

  ngOnInit() {}
}

Solution 9 - Angular

You can make a custom Http Service (using HttpClient) which maintains a list of pending requests. Whenever you fire a http us this custom service instead of Http/HttpClient,now push the subscriptions to a list and on return of the response pop that subscription out. Using this you will have all the incomplete subscriptions in a list.

Now in the same custom service Inject router in the constructor and subscribe on it to get the route change events. Now whenever this observable emits, all you need to do is to unsubscribe all the subscriptions present in the list and pop all the elements from it.

If you need code snippet, do mention in comment.

Solution 10 - Angular

I don't think it's a good idea to cancel requests on route change level because one will lose granularity.

For instance, maybe you want to cancel a request on one component and not on another because it's not going to destory. Most importantly, what about background requests? It will be very trickey to debug why some requests have randomly been cancelled.

But its generally a good idea to cancel get requests whose component is going to destroy, regardless of route change.


Unsubscribing from observables on destroy

If you want to make your life easy then use until-destroy. It will automatically unsubscribe all observables when your component is going going to be destroyed (ngOnDestroy). It's granule enough and more general (not just HttpRequests but all observables will been unsubscribed from)

import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
     
@UntilDestroy()
@Component({})
export class InboxComponent {
  ngOnInit() {
    interval(1000)
      .pipe(untilDestroyed(this))
      .subscribe();
  }
}

Solution 11 - Angular

Here is a very simple, tested, and working example

import { Component, ViewChild, ElementRef } from "@angular/core";
import { DataService } from "../services/data.service";

@Component({
  selector: "app-home",
  templateUrl: "home.page.html",
  styleUrls: ["home.page.scss"],
})
export class HomePage {
  @ViewChild("image") image: ElementRef;
  loading = false;
  subscriptions = [];
  constructor(private dataService: DataService) {}

  start() {
    this.loading = true;
    this.image.nativeElement.classList.add("animate");
    const subscription = this.dataService
      .paymentRequest()

      .subscribe(
        (data) => {
          this.image.nativeElement.classList.remove("animate");
          this.loading = false;
          console.log(data);
        },
        (error) => this.start()
      );
    this.subscriptions.push(subscription);
  }

  stop() {
    this.loading = false;
    this.image.nativeElement.classList.remove("animate");
    this.subscriptions.forEach((subscription) => {
      subscription.unsubscribe();
    });
    this.subscriptions = [];
    // This completes the subject properlly.
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSibirajView Question on Stackoverflow
Solution 1 - AngularAlexis FacquesView Answer on Stackoverflow
Solution 2 - AngularBladitoView Answer on Stackoverflow
Solution 3 - AngularAnton LeeView Answer on Stackoverflow
Solution 4 - AngularAluan HaddadView Answer on Stackoverflow
Solution 5 - AngularVala KhosraviView Answer on Stackoverflow
Solution 6 - AngularChandruView Answer on Stackoverflow
Solution 7 - Angularsanjil shakyaView Answer on Stackoverflow
Solution 8 - AngularDeunzView Answer on Stackoverflow
Solution 9 - AngularSumit AgarwalView Answer on Stackoverflow
Solution 10 - AngularhananView Answer on Stackoverflow
Solution 11 - AngularKrishna KarkiView Answer on Stackoverflow