Dipak Dipak - 26 days ago 12
AngularJS Question

how to make synchronous http request in angular js

how to make blocking http request in angular js so that i can use the $http response on very next line in angular js.

here $http object doesn't return the result on next line so that i can pass the $http response on fullcalender a javascript library.

here $scope.data returns blank value.

Sample code below

$http.get('URL').success(function(data){

$scope.data = data;

});

$.fullCalender({
data: $scope.data
});

Answer

You can use promises for that.

here is an example:

$scope.myXhr = function(){

    var deferred = $q.defer();

    $http({
        url: 'ajax.php',
        method: 'POST',
        data:postData,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        })
        //if request is successful
        .success(function(data,status,headers,config){

            //resolve the promise
            deferred.resolve('request successful');

        })
        //if request is not successful
        .error(function(data,status,headers,config){
            //reject the promise
            deferred.reject('ERROR');
        });

    //return the promise
    return deferred.promise;
}

$scope.callXhrAsynchronous = function(){

    var myPromise = $scope.myXhr();

    // wait until the promise return resolve or eject
    //"then" has 2 functions (resolveFunction, rejectFunction)
    myPromise.then(function(resolve){
        alert(resolve);
        }, function(reject){
        alert(reject)      
    });

}