AngularJs: $ http Synchronous Call

I have a service to call an API as follows:

getValue: function(input) { var deferred, url; deferred = $q.defer(); url = "url"; $http.post(url, input).success(function(data, status, headers, config) { return deferred.resolve({ success: true, data: data, status: status, headers: headers, config: config }); }).error(function(data, status, headers, config) { return deferred.resolve({ success: false, data: data, status: status, headers: headers, config: config }); }); return deferred.promise; } 

But it is asynchronous. How can I convert it to synchronization (I want to make it wait until I get the result)?

+6
source share
1 answer

No, this is not possible with Angular.

See https://github.com/angular/angular.js/blob/master/src/ng/httpBackend.js#L51 where XMLHttpRequest opens with

 xhr.open(method, url, true); 

The third parameter in xhr.open() can be set to false or true , where false is synchronous and true is asynchronous. In the case of Angular, it is tightly bound to true , so all outgoing calls will be asynchronous.

Use the .success() callback to wait until the asynchronous call returns, and then do what you want to do there.

As suggested in the comments, you can also make calls through raw javascript, jQuery or any other library that supports synchronous calls, but I would recommend using callbacks / defers with an asynchronous call to Angular, because synchronous calls block and block poorly.

+6
source

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


All Articles