How to cancel a HTTPRequest in Angular 2? How to cancel a HTTPRequest in Angular 2? angular angular

How to cancel a HTTPRequest in Angular 2?


You can use the following simple solution:

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


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


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