angular學習筆記(二十六)-$http(4)-設定請求超時

詩&遠方發表於2014-07-31

本篇主要講解$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)

相關文章