How to cancel a HTTPRequest in Angular 2?

2019-01-14 05:24发布

问题:

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

回答1:

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



回答2:

You can the use the following simple solution.

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


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



回答4:

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