angular學習筆記(二十六)-$http(4)-佈建要求逾時

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   資料   for   

本篇主要講解$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-urlencodedapp.use(bodyParser.urlencoded({ extended: false }));// parse application/jsonapp.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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.