如何在角度js中进行同步http请求

时间:2014-11-05 06:14:02

标签: angularjs

如何在AngularJS中阻止http请求,以便我可以在下一行使用$ http响应?

在以下示例中,$http对象不会将结果返回到下一行,以便我可以将此结果传递给JavaScript库fullcalender(),因为$scope.data返回空白值。

这是示例代码:

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

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

3 个答案:

答案 0 :(得分:2)

你不能,你需要通过承诺来处理它,但你可以尝试这样做:

$http.get('URL').success(function(data){
    angular.copy(data, $scope.data);
});

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

但大多数人都会这样做

$http.get('URL').success(function(data){
    $.fullCalender({
        data: data
    });
});

如果你的fullCalender对象不能处理异步数据,你可能需要将它包装在像ng-if这样的东西中,或者在提供数据时强制它重绘。您还可以强制控制器在使用路径解析加载数据之前不加载。

答案 1 :(得分:2)

您可以使用promises

这是一个例子:

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

}

答案 2 :(得分:1)

以下是一个实际答案,由用户Kirill Slatin提供,他将答案作为评论发布。答案底部的实际使用示例。

如果像我一样,你需要将该响应对象用作范围变量,那么这应该有效:

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

$scope.data = data;
$.fullCalender = $scope.data;
$scope.$apply()
});

$scope.$apply()将保留响应对象,以便您可以使用该数据。

-

为什么需要这样做?

我一直在尝试为我的食谱应用创建一个“编辑”页面。 我需要使用所选配方的数据填充表单。 在发出我的GET请求并将响应数据传递给$ scope.form后,我什么都没有...... $scope.$apply()Kirill Slatin帮了大忙。干杯队友!

以下是来自editRecipeController的示例:

  $http.get('api/recipe/' + currentRecipeId).then(
    function (data) {
      $scope.recipe = data.data;
      $scope.form = $scope.recipe;
      $scope.$apply()
    }
);

希望有所帮助!