How to cancel a HTTPRequest in Angular 2?

How to cancel a HTTPRequest in Angular 2?

I know how to reject the request promise only.

return new Promise((resolve, reject) => {
    this.currentLoading.set(url, {resolve, reject});

    this.http.get(url, {headers: reqHeaders})
        .subscribe(
            (res) => {
                res = res.json();

                this.currentLoading.delete(url);
                this.cache.set(url, res);

                resolve(res);
            }
        );
});

Solution 1:

You can use the following simple solution:

if ( this.subscription ) {
   this.subscription.unsubscribe();
}
this.subscription = this.http.get( 'awesomeApi' )
 .subscribe((res)=> {
  // your awesome code..
})

Solution 2:

You can call unsubscribe

let sub = this.http.get(url, {headers: reqHeaders})
            .subscribe(
                (res) => {
                    res = res.json();

                    this.currentLoading.delete(url);
                    this.cache.set(url, res);

                    resolve(res);
                }
            );

sub.unsubscribe();

More info here: http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http

Solution 3:

You can use SwitchMap on the observable which will cancel any previous request's responses and only request the latest:

https://www.learnrxjs.io/operators/transformation/switchmap.html