How to $http Synchronous call with AngularJS
Asked Answered
R

7

133

Is there any way to make a synchronous call with AngularJS?

The AngularJS documentation is not very explicit or extensive for figuring out some basic stuff.

ON A SERVICE:

myService.getByID = function (id) {
    var retval = null;

    $http({
        url: "/CO/api/products/" + id,
        method: "GET"
    }).success(function (data, status, headers, config) {

        retval = data.Data;

    });

    return retval;
}
Rosco answered 26/10, 2012 at 13:45 Comment(4)
See also groups.google.com/d/topic/angular/qagzXXhS_VI/discussion for some ideas about how to deal with the asynchronous behavior: events, $watch, preload on the server side, use the promise returned from $http.Fatalism
Asynchronous is always better, especially when you have promises.Overtrick
Many times, you can avoid synchronous calls. See how $resource works #11966752.Isacco
@AndrewJoslin Asynchronous is worse when you need ordered delivery.Bedaub
B
115

Not currently. If you look at the source code (from this point in time Oct 2012), you'll see that the call to XHR open is actually hard-coded to be asynchronous (the third parameter is true):

 xhr.open(method, url, true);

You'd need to write your own service that did synchronous calls. Generally that's not something you'll usually want to do because of the nature of JavaScript execution you'll end up blocking everything else.

... but.. if blocking everything else is actually desired, maybe you should look into promises and the $q service. It allows you to wait until a set of asynchronous actions are done, and then execute something once they're all complete. I don't know what your use case is, but that might be worth a look.

Outside of that, if you're going to roll your own, more information about how to make synchronous and asynchronous ajax calls can be found here.

I hope that is helpful.

Betancourt answered 26/10, 2012 at 14:0 Comment(10)
Can you please code snippet to achieve using $q service. I tried many options but it is working in an asynchronous manner.Millinery
There are places where it can make sense, e.g. just when the user closes the browser (onbeforeunload), if you want to save you have to send a sync request, another option is to show a dialog cancel, and then relaunch the window close?Sputum
@Venkat: I know this is a late reply, but as I said in the answer, the call will always be "asynchronous" you just have to use $q to make it wait for the the response, then continue your logic inside of the .then(callback). something like: doSomething(); $http.get('/a/thing').then(doEverythingElse);.Betancourt
The following video helped me in studying promises AngularJS Promises with $qBathulda
@circuitry This answer needs a code example of what? The question was, specifically, how to make $http behave synchronously in Oct. 2012. At the time that wasn't possible. So a code example would have been like throw new Error('you cannot do this').Betancourt
@BenLesh, When I come here I'm looking for solutions. You said "maybe you should look into promises and the $q service." What would that look like? Also if the answer is out of date you could update it. Your post did not provide a code example of a workaround, which is what I was looking for.Insouciance
@Insouciance it's a free answer on a free site given with time I volunteered. 82 people found it useful. Sorry you didn't. Feel free to update the answer yourself, if you like. I honestly would, but I don't have the time.Betancourt
@BenLesh I'm not unappreciative of the time you put in, or the time anyone puts in. I'm free to down-vote your answer and say that it would have been helpful to me if an example was provided. I saw your answer, it didn't help me, so I down voted it and closed the tab, and went back to google to try to find an answer that was more helpful to me. It's not the end of the world when someone down-votes your answer, and tells you how it could be improved. Would you have preferred I down-voted without leaving a comment as to why? Just being honest.Insouciance
Also just because you spent time on the answer doesn't make it any more helpful. Here is an example that was helpful to me: #16228144Insouciance
I really don't care about your downvote. Or the votes. I rarely answer anything on SO anymore. "When I come here I'm looking for solutions" "if the answer is out of date you could update it". It reads like entitlement to me. Perhaps that's a misunderstanding, but it wouldn't be the first time I've seen that on SO.Betancourt
J
12

I have worked with a factory integrated with google maps autocomplete and promises made​​, I hope you serve.

http://jsfiddle.net/the_pianist2/vL9nkfe3/1/

you only need to replace the autocompleteService by this request with $ http incuida being before the factory.

app.factory('Autocomplete', function($q, $http) {

and $ http request with

 var deferred = $q.defer();
 $http.get('urlExample').
success(function(data, status, headers, config) {
     deferred.resolve(data);
}).
error(function(data, status, headers, config) {
     deferred.reject(status);
});
 return deferred.promise;

<div ng-app="myApp">
  <div ng-controller="myController">
  <input type="text" ng-model="search"></input>
  <div class="bs-example">
     <table class="table" >
        <thead>
           <tr>
              <th>#</th>
              <th>Description</th>
           </tr>
        </thead>
        <tbody>
           <tr ng-repeat="direction in directions">
              <td>{{$index}}</td>
              <td>{{direction.description}}</td>
           </tr>
        </tbody>
     </table>
  </div>

'use strict';
 var app = angular.module('myApp', []);

  app.factory('Autocomplete', function($q) {
    var get = function(search) {
    var deferred = $q.defer();
    var autocompleteService = new google.maps.places.AutocompleteService();
    autocompleteService.getPlacePredictions({
        input: search,
        types: ['geocode'],
        componentRestrictions: {
            country: 'ES'
        }
    }, function(predictions, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            deferred.resolve(predictions);
        } else {
            deferred.reject(status);
        }
    });
    return deferred.promise;
};

return {
    get: get
};
});

app.controller('myController', function($scope, Autocomplete) {
$scope.$watch('search', function(newValue, oldValue) {
    var promesa = Autocomplete.get(newValue);
    promesa.then(function(value) {
        $scope.directions = value;
    }, function(reason) {
        $scope.error = reason;
    });
 });

});

the question itself is to be made on:

deferred.resolve(varResult); 

when you have done well and the request:

deferred.reject(error); 

when there is an error, and then:

return deferred.promise;
Juli answered 26/6, 2014 at 8:57 Comment(0)
C
5
var EmployeeController = ["$scope", "EmployeeService",
        function ($scope, EmployeeService) {
            $scope.Employee = {};
            $scope.Save = function (Employee) {                
                if ($scope.EmployeeForm.$valid) {
                    EmployeeService
                        .Save(Employee)
                        .then(function (response) {
                            if (response.HasError) {
                                $scope.HasError = response.HasError;
                                $scope.ErrorMessage = response.ResponseMessage;
                            } else {

                            }
                        })
                        .catch(function (response) {

                        });
                }
            }
        }]


var EmployeeService = ["$http", "$q",
            function ($http, $q) {
                var self = this;

                self.Save = function (employee) {
                    var deferred = $q.defer();                
                    $http
                        .post("/api/EmployeeApi/Create", angular.toJson(employee))
                        .success(function (response, status, headers, config) {
                            deferred.resolve(response, status, headers, config);
                        })
                        .error(function (response, status, headers, config) {
                            deferred.reject(response, status, headers, config);
                        });

                    return deferred.promise;
                };
Chemoreceptor answered 4/9, 2015 at 10:37 Comment(0)
D
4

I recently ran into a situation where I wanted to make to $http calls triggered by a page reload. The solution I went with:

  1. Encapsulate the two calls into functions
  2. Pass the second $http call as a callback into the second function
  3. Call the second function in apon .success
Dehumidify answered 21/7, 2015 at 15:1 Comment(1)
What if its a for loop, with n times calling server.Unheard
C
2

Here's a way you can do it asynchronously and manage things like you would normally. Everything is still shared. You get a reference to the object that you want updated. Whenever you update that in your service, it gets updated globally without having to watch or return a promise. This is really nice because you can update the underlying object from within the service without ever having to rebind. Using Angular the way it's meant to be used. I think it's probably a bad idea to make $http.get/post synchronous. You'll get a noticeable delay in the script.

app.factory('AssessmentSettingsService', ['$http', function($http) {
    //assessment is what I want to keep updating
    var settings = { assessment: null };

    return {
        getSettings: function () {
             //return settings so I can keep updating assessment and the
             //reference to settings will stay in tact
             return settings;
        },
        updateAssessment: function () {
            $http.get('/assessment/api/get/' + scan.assessmentId).success(function(response) {
                //I don't have to return a thing.  I just set the object.
                settings.assessment = response;
            });
        }
    };
}]);

    ...
        controller: ['$scope', '$http', 'AssessmentSettingsService', function ($scope, as) {
            $scope.settings = as.getSettings();
            //Look.  I can even update after I've already grabbed the object
            as.updateAssessment();

And somewhere in a view:

<h1>{{settings.assessment.title}}</h1>
Conceptacle answered 2/2, 2016 at 13:51 Comment(0)
H
0

Since sync XHR is being deprecated, it's best not to rely on that. If you need to do a sync POST request, you can use the following helpers inside of a service to simulate a form post.

It works by creating a form with hidden inputs which is posted to the specified URL.

//Helper to create a hidden input
function createInput(name, value) {
  return angular
    .element('<input/>')
    .attr('type', 'hidden')
    .attr('name', name)
    .val(value);
}

//Post data
function post(url, data, params) {

    //Ensure data and params are an object
    data = data || {};
    params = params || {};

    //Serialize params
    const serialized = $httpParamSerializer(params);
    const query = serialized ? `?${serialized}` : '';

    //Create form
    const $form = angular
        .element('<form/>')
        .attr('action', `${url}${query}`)
        .attr('enctype', 'application/x-www-form-urlencoded')
        .attr('method', 'post');

    //Create hidden input data
    for (const key in data) {
        if (data.hasOwnProperty(key)) {
            const value = data[key];
            if (Array.isArray(value)) {
                for (const val of value) {
                    const $input = createInput(`${key}[]`, val);
                    $form.append($input);
                }
            }
            else {
                const $input = createInput(key, value);
                $form.append($input);
            }
        }
    }

    //Append form to body and submit
    angular.element(document).find('body').append($form);
    $form[0].submit();
    $form.remove();
}

Modify as required for your needs.

Hibbert answered 12/3, 2018 at 7:35 Comment(0)
E
-4

What about wrapping your call in a Promise.all() method i.e.

Promise.all([$http.get(url).then(function(result){....}, function(error){....}])

According to MDN

Promise.all waits for all fulfillments (or the first rejection)

Encarnacion answered 24/5, 2017 at 13:23 Comment(8)
what are you talking about? the question has nothing to do with multiple promises...Downe
It will wait for one or more promise to complete!Encarnacion
have you used this to see how it works? Promise.all will return another promise, it does not transform async into sync callsDowne
Hmm... it seems that the MDN documentation may be ambiguous... It does not actually WAIT as stated in their documentation.Encarnacion
Welcome to SO. Please read this how-to-answer for providing quality answer.Payne
I wouldn't say it's ambiguous because waits for all fulfillments is not the same thing as synchronous code in JS. It waits for fulfillment in the sense that you can use it to make sure a number of X promises all finish before you get the results and can do something else.Downe
You are right. Subtle but important difference. Chaining is not the same as synchrony although one could be an awkward way of implementing the other. For that reason I will forebear to suggest a way of getting the correct order of execution using promises. There must be a simpler way.Encarnacion
As the OP asked, he wants a sync call to make another maybe to use its data next, using promise all we will get a concurrence here event waiting all to get its result.Bes

© 2022 - 2024 — McMap. All rights reserved.