Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make synchronous http request in angular js

Tags:

How to make blocking http request in AngularJS so that i can use the $http response on very next line?

In the following example, $http object doesn't return the result to the next line so that I can pass this result to fullcalender(), a JavaScript library, because $scope.data returns blank value.

This is the sample code:

$http.get('URL').success(function(data){
    $scope.data = data;
});

$.fullCalender({
    data: $scope.data
});
like image 656
Dipak Avatar asked Nov 05 '14 06:11

Dipak


People also ask

Is HTTP request is synchronous or asynchronous in Angularjs?

The problem is as follows, $http. get is asynchronous, before the response is fetched, the function returns. Therefore the calling function gets the data as empty string.

Is angular asynchronous or synchronous?

Angular makes use of observables as an interface to handle a variety of common asynchronous operations. For example: The HTTP module uses observables to handle AJAX requests and responses. The Router and Forms modules use observables to listen for and respond to user-input events.


1 Answers

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)      
    });

}
like image 188
Giwwel Avatar answered Sep 19 '22 00:09

Giwwel