本篇主要讲解$http(config)的config中的timeout项:
$http({ timeout: number })
数值,从发出请求开始计算,等待的毫秒数,超过这个数还没有响应,则返回错误
demo:
html:
<!DOCTYPE html>
<html ng-app = 'HttpGet'>
<head>
<title>18.4 $http(2)</title>
<meta charset="utf-8">
<script src="angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller = "dataController">
<span>{{data}}</span>
</div>
</body>
</html>
js:
var jsonData = {name:"code_bunny"}; var httpGet = angular.module('HttpGet',[]); httpGet.factory('getData',function($http,$q){
return function(){
var defer = $q.defer();
$http({
method:'post',
url:'/api/user',
data: jsonData,
headers: {'Authorization':'code_bunny'},
timeout: 1000
}).success(function(data,status,headers,config){
defer.resolve(data);
}).error(function(data,status,headers,config){
defer.reject(data)
});
return defer.promise
}
});
httpGet.controller('dataController',function($scope,getData){
$scope.data = getData()
});
nodejs:
var express = require('express');
var bodyParser = require('body-parser');
var app = express(); // parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false })); // parse application/json
app.use(bodyParser.json()); app.use(express.static(__dirname+'')); var data = "name=code_bunny&age=3"; app.post('/api/user',function(req,res){
console.log(req.body);
setTimeout(function(){
res.send(data)
},2000)
}); app.listen(3000);
如代码所示,我们在后台设置2000毫秒以后返回内容,但是在$http的congif里设置等待超时为1000毫秒,所以,还不等到后台返回数据,请求就会被取消:
*注意: timeout只能在某个单独的$http()里面配置,不能通过$httpProvider.defaults.timeout进行配置
完整代码路径:https://github.com/OOP-Code-Bunny/angular/tree/master/OREILLY/18.4%20%24http(2)