延迟 angular.js $http 服务

编程入门 行业动态 更新时间:2024-10-28 12:25:21
本文介绍了延迟 angular.js $http 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一些 Angular 工厂,用于对遗留的 ASP.NET .asmx Web 服务进行 ajax 调用,如下所示:

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

我正在本地网络上进行测试,因此响应时间太"了.是否有一种聪明的方法可以将 $http 延迟几秒钟以模拟错误连接?

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?

或者我是否需要将所有对工厂方法的调用都包含在 $timeout 中?

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

推荐答案

有趣的问题!

正如您自己提到的,$timeout 是延迟呼叫的最合乎逻辑的选择.您可以推送一个响应拦截器,将 $http 承诺包装在 $timeout 承诺中,而不是到处都有 $timeout 调用,如概念上所述在 $http 的文档中,并在您的配置块之一.这意味着所有 $http 调用都会受到 $timeout 延迟的影响.类似的东西:

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 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-21 14:55:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1004775.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:angular   js   http

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!