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


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM