How to cancel an $http request in AngularJS?

前端 未结 8 959
面向向阳花
面向向阳花 2020-11-22 09:49

Given a Ajax request in AngularJS

$http.get(\"/backend/\").success(callback);

what is the most effective way to cancel that request if anot

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 10:17

    here is a version that handles multiple requests, also checks for cancelled status in callback to suppress errors in error block. (in Typescript)

    controller level:

        requests = new Map>();
    

    in my http get:

        getSomething(): void {
            let url = '/api/someaction';
            this.cancel(url); // cancel if this url is in progress
    
            var req = this.$q.defer();
            this.requests.set(url, req);
            let config: ng.IRequestShortcutConfig = {
                params: { id: someId}
                , timeout: req.promise   // <--- promise to trigger cancellation
            };
    
            this.$http.post(url, this.getPayload(), config).then(
                promiseValue => this.updateEditor(promiseValue.data as IEditor),
                reason => {
                    // if legitimate exception, show error in UI
                    if (!this.isCancelled(req)) {
                        this.showError(url, reason)
                    }
                },
            ).finally(() => { });
        }
    

    helper methods

        cancel(url: string) {
            this.requests.forEach((req,key) => {
                if (key == url)
                    req.resolve('cancelled');
            });
            this.requests.delete(url);
        }
    
        isCancelled(req: ng.IDeferred<{}>) {
            var p = req.promise as any; // as any because typings are missing $$state
            return p.$$state && p.$$state.value == 'cancelled';
        }
    

    now looking at the network tab, i see that it works beatuifully. i called the method 4 times and only the last one went through.

提交回复
热议问题