httppromiseangular

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

  • 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