2014-11-05 65 views
18

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

在下面的例子中,$http对象不将结果返回到下一行,这样我可以将此结果传递给fullcalender(),一个JavaScript库,因为$scope.data返回空值。

这是示例代码:

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

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

有什么办法可以避免这种情况? Javascript是单线程的,并且在等待响应时发出同步HTTP请求会阻止整个浏览器。这不应该是您的首选解决方案。 – GregL 2014-11-05 06:16:13

+1

您不能简单地将调用移动到fullCalendar到成功回调并设置数据等于回调的数据参数? – Scott 2014-11-05 06:17:00

+0

当我在回调中使用fullcalendar数据时,它不显示在模板上。 – Dipak 2014-11-05 06:24:59

回答

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

} 
+1

不返回'$ http'创建的promise的原因是什么? IT是一个糟糕的做法,以延迟现有的承诺 – 2015-07-15 21:53:58

+0

由于'$ http'创建的承诺是异步 – stevemao 2015-07-16 04:03:26

+63

我想知道为什么这被接受为答案。 OP询问**同步**,并且你回答**异步** – KingJulian 2015-07-27 18:37:27

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

这里是一个实用的答案,用户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() 
    } 
); 

希望帮助!