How to cancel a HTTPRequest in Angular 2?

HttpPromiseAngular

Http Problem Overview


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);
            }
        );
});

Http Solutions


Solution 1 - Http

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 - Http

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 - 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

Solution 4 - Http

A little late for the party, but here is my take:

import { Injectable } from '@angular/core'
import { Http } from '@angular/http'
import { Observable } from 'rxjs/Observable'
import { Subscriber } from 'rxjs/Subscriber'

@Injectable ()
export class SomeHttpServiceService {
  private subscriber: Subscriber<any>
  constructor(private http: Http){ }

  public cancelableRequest() {
    let o = new Observable(obs => subscriber = obs)
    return this.http.get('someurl').takeUntil(o)
      .toPromise() //I dont like observables
      .then(res => {
        o.unsubscribe
        return res
      })
  }
  public cancelRequest() {
    subscriber.error('whatever')
  }
}

This allows you to manually cancel a request. I sometimes end up with an observable or promise that will make changes to a result on the page. If the request was initiated automatically (user didn't type anyting in a field for x millis) being able to abort the request is nice (user is suddenly typing something again)...

takeUntil should also work with a simple timeout (Observable.timer) if that is what you are looking for https://www.learnrxjs.io/operators/filtering/takeuntil.html

Solution 5 - Http

Use switchMap [docs], which will cancel all in-flight requests and use only the latest.

get(endpoint: string): Observable<any> {
        const headers: Observable<{url: string, headers: HttpHeaders}> = this.getConfig();
        return headers.pipe(
            switchMap(obj => this.http.get(`${obj.url}${endpoint}`, { headers: obj.headers, params: params }) ),
            shareReplay(1)
        );
    }

shareReplay will emit the latest value for any late subscribers.

Solution 6 - Http

This is a great thread, and I have a little more info to provide. I have an API call that could potentially go on for a very long time. So I needed the previous request to cancel with a timeout. I just figured out today that I can add a timeout operator to the pipe function. Once the timeout completes its count, that will cancel the previous HTTP request.

Example...

return this.exampleHttpRequest()
  .pipe(
    timeout(3000),
    catchError(err => console.log(error)
)

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
Questiontom10271View Question on Stackoverflow
Solution 1 - HttpErvTheDevView Answer on Stackoverflow
Solution 2 - HttpTGHView Answer on Stackoverflow
Solution 3 - HttpBen TaliadorosView Answer on Stackoverflow
Solution 4 - HttpclearfixView Answer on Stackoverflow
Solution 5 - HttpIanView Answer on Stackoverflow
Solution 6 - HttpAndrew GremlichView Answer on Stackoverflow