Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get $http readyState on AngularJS?

How can I get $http readyState, use like this:

var request, interval;

request = $http
  .post('/user/info', {...})
  .success(...);

interval = setInterval(function(){
  if(request.readyState < 3)
    return;

  prepare(request.data, request.headers);
  clearInterval(interval)
}, 10);

function prepare(data, headers){
  ...
}

I have no idea how to do this without changing the angular.js file. Is it possible add some features to the service via $httpBackend or something other?

like image 207
Turar Abu Avatar asked Dec 05 '25 19:12

Turar Abu


1 Answers

With AngularJS 1.5.5, support was added for additional handling of XHR events:

$http Arguments - Config

Object describing the request to be made and how it should be processed. The object has following properties:

  • eventHandlers - {Object} - Event listeners to be bound to the XMLHttpRequest object. To bind events to the XMLHttpRequest upload object, use uploadEventHandlers. The handler will be called in the context of a $apply block.
  • uploadEventHandlers - {Object} - Event listeners to be bound to the XMLHttpRequest upload object. To bind events to the XMLHttpRequest object, use eventHandlers. The handler will be called in the context of a $apply block.

— AngularJS $http Service API Reference - Http Arguments

Use the eventHandlers property of the config object to add an event handller that gets the XHR readyState:

The DEMO

angular.module("app",[])
.run(function($rootScope, $http){
  var eventHandlers = {readystatechange: readyStateChangeHandler};
  var config = { eventHandlers: eventHandlers }; 
  $rootScope.messageList = [];
  
  function readyStateChangeHandler(ev) {
    var message = "readyState: "+ev.target.readyState;
    console.log(message);
    $rootScope.messageList.push(message);
  }
  
  $http.get("//httpbin.org/anything",config)
    .then(function(response){
      console.log("OK");
      //console.log(response);
  }).catch(function(response){
      console.log("ERROR");
      //console.log(response); 
  })
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
    <div ng-repeat="m in messageList">
      {{m}}  
    </div>
  </body>
like image 156
georgeawg Avatar answered Dec 07 '25 15:12

georgeawg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!