how to make synchronous http request in angular js

前端 未结 3 1773
北海茫月
北海茫月 2020-12-03 10:27

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

3条回答
  •  执笔经年
    2020-12-03 11:06

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

提交回复
热议问题