Delay an angular.js $http service

前端 未结 8 1199
感动是毒
感动是毒 2021-01-31 16:32

I have some angular factories for making ajax calls towards legacy ASP.NET .asmx web services like so:

module.factory(\'productService\', [\"$http\",
function ($         


        
8条回答
  •  忘了有多久
    2021-01-31 16:38

    You can achieve this using the promise api combined with a $timeout. The $http.post function returns a promise from which you can call .success and .error (these are http specific methods). This promise is resolved when the http request is complete. If you build your own promise then you can tell it to delay 2 seconds and then resolve when the http request is complete:

    module.factory('productService', function ($http, $q, $timeout) {
    
        return {
            getSpecialProducts: function (data) {
                var defer = $q.defer();
                $http.post('/ajax/Products.asmx/GetSpecialProducs', data).success(
                  function(data) {
                    // successful http request, resolve after two seconds
                    $timeout(function() {
                        defer.resolve(data);
                    }, 2000)
                }).error(function() {
                    defer.reject("Http Error");
                })
                return defer.promise;
            }
        }
    
    });
    

    But note - you will have to use promise.then(successCallback, errorCallback) functionality - that is, you'll lose the ability to access http headers, status & config from your controllers/directives unless you explicitly supply them to the object passed to defer.resolve({})

    Links:

    • Defer/Promise Api
    • Http/Promise Api
    • Resolve egghead video

提交回复
热议问题