Angular does not make $ http requests immediately

I have a directive that responds to a Blur event that is fired from an input element, and then ultimately causes the Angular $ http service to be called to make the corresponding HTTP request.

The $ http service is called correctly and generates the expected promise, however the actual HTTP request is not received immediately. It only starts after you have done other kinds of DOM interactions.

Why is the request not being executed immediately? And how can I get them to do it immediately?

Angular v1.1.5

+4
source share
3 answers

Cause

In the end, I found the answer in questions about GitHub ( https://github.com/angular/angular.js/issues/2442 ):

v1.1.4 ... changed the way $ http works so that it is scheduled on nextTick instead of starting immediately. This means that if your $ http is planned for something that does not cause $ digest to fail, your request will not be sent. You can verify that this is the behavior that you see by clicking on the page several times (anywhere), and you will see that your request is disconnected.

Decision

As suggested, I triggered the $ digest loop, which caused my requested $ http requests to start immediately.

scope.$apply(); 
+19
source

In addition to the other reasons above ... If you used ... injector.get ("$ http") manually from code outside of angular, then you may have received the $ http service from the wrong injector instance.

This is what happened to us, and it took a very long time to sort it out. In this case, the request is not sent even if $ http is enclosed in $ apply.

+2
source

This situation occurs when an event is fired β€œoutside” of Angular, and Angular knows nothing about it.

The blur event comes from the DOM, or maybe you have an AJAX callback that triggers an update. You will notice that nothing happens until you somehow interact with the application that causes Angular to wake up. George Thomas's answer is correct: you must set Angular $scope so that he knows about this event, but, according to Angular developers, a more correct way is to wrap your code in a $apply() function like this

 $("#myElement").blur(function() { $scope.$apply(function() { $http({method: 'GET', url: '/someUrl'}); }); }); 

Thus, errors in the code correctly propagate to Angular.

I found this information in an extremely good presentation on the Misko Hevery directives - the developer who created them: http://www.youtube.com/watch?v=WqmeI5fZcho . If you use Angular for a while in a project, but are not quite sure what is really happening, this video is 50 minutes of your life well spent!

+1
source

Source: https://habr.com/ru/post/1485578/


All Articles