本文介绍了耽误angular.js $ http服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些角度工厂制作AJAX对传统ASP.NET调用的.asmx Web服务,像这样:

  module.factory('productService',[$ HTTP
功能($ HTTP){
    返回{
        getSpecialProducts:功能(数据){
            返回$ http.post('/ AJAX / Products.asmx / GetSpecialProducs',数据);
        }
    }
}]);

我在本地网络上,以便响应时间太好测试。有来自使得调用模拟接触不良延迟$ HTTP几秒钟的一个聪明的办法?

或者我需要换行到工厂方法的所有调用在$超时?

  $超时(函数(){
  productService.getSpecialProducs(数据).success(成功).error(错误);
} $ scope.MOCK_ajaxDelay);


解决方案

有趣的问题!

就像你提到的自己, $超时是一个延迟调用最合理的选择。而不必 $超时来电随处可见,你可以推动一个包装在<$的 $ HTTP 承诺的响应拦截C $ C> $超时诺言,为的,并在配置块中的一个注册。这意味着所有的 $ HTTP 调用由 $超时延迟的影响。沿着线的东西:

  $ httpProvider.interceptors.push(函数($超时){
    返回{
        回应:功能(响应){
            返回$超时(函数(){
                返回响应;
            },2500);
        }
    };
});

作为奖励,你的模拟连接不良?,你可以拒绝或什么都不做,随意,太。 嘿嘿嘿。

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

module.factory('productService', ["$http",
function ($http) {
    return {
        getSpecialProducts: function (data) {
            return $http.post('/ajax/Products.asmx/GetSpecialProducs', data);
        }
    }
} ]);

I'm testing on a local network so response times are "too" good. Is there a smart way of delaying the $http a couple of seconds from making the call to simulate a bad connection?

Or do I need to wrap all calls to the factory methods in a $timeout ?

$timeout(function() {
  productService.getSpecialProducs(data).success(success).error(error);
}, $scope.MOCK_ajaxDelay);
解决方案

Interesting question!

As you mentioned yourself, $timeout is the most logical choice for a delayed call. Instead of having $timeout calls everywhere, you could push a response interceptor that wraps the $http promise in a $timeout promise, as conceptually outlined in the documentation of $http, and register it in one of your configuration blocks. This means all $http calls are affected by the $timeout delay. Something along the lines of:

$httpProvider.interceptors.push(function($timeout) {
    return {
        "response": function (response) {
            return $timeout(function() {
                return response;
            }, 2500);
        }
    };
});

As a bonus to your "to simulate a bad connection?", you could reject or do absolutely nothing randomly, too. Heh heh heh.

这篇关于耽误angular.js $ http服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 13:41