2015-10-24 41 views
2

我们可以通过$http.get('url', {timeout: 5000});手动设置每个$http的超时时间是否可以设置全局$http超时一次,它将应用于整个应用程序?

+0

如果你在一个服务中包装你的http调用,那么是的。或用户某种$ http拦截服务,也可以做...如果你需要示例让我知道 –

+0

@ Jony-Y非常感谢您的评论。如果你能够举一个例子说明你的建议是否可以完成,那将会很好。 – user1995781

+0

非常像@NetSou在答案中显示的...只需将您的$超时添加到您的帐号或您想要它执行的任何操作 –

回答

7

您可以使用请求http拦截器。喜欢这个。

angular.module('myapp') 
    .factory('timeoutHttpInterceptor', function() { 
    return { 
     'request': function(config) { 
     config.timeout = 10000; 
     return config; 
     } 
    }; 
}); 

然后在注入的.config $ httpProvider和做到这一点:

$httpProvider.interceptors.push('timeoutHttpInterceptor'); 

,或者你可以这样做也:

// this custom config could actually be a part of a more general app-level config 
    // so that you need to inject only one global config 
    myApp.value('http_defaults', { 
    timeout: 150 
    }); 

在这里你可以看到更简单的方式注入上述每个控制器中的http_defaults是您使用的$http。并设置http请求的所有默认属性。

myApp.controller('myCtrl', function ($scope, $http, http_defaults) { 

    // in case you need to change the default values for this specific request 
     // angular.extend(http_defaults, {timeout: 300}); 

     $http.get("/xyz", http_defaults) 
     .success(success) 
     .error(error); 
    }; 
}); 

You can refer this

我会建议使用第一个选项。

+2

您是否知道$ http服务的默认超时值?还是没有默认超时(等待)? – demaniak