Angularjs 如何在angular js中进行同步http请求

Angularjs 如何在angular js中进行同步http请求,angularjs,Angularjs,如何在AngularJS中阻塞http请求,以便在下一行中使用$http响应 在下面的示例中,$http对象不会将结果返回到下一行,因此我可以将此结果传递给JavaScript库fullCalendar(),因为$scope.data返回空值 这是示例代码: $http.get('URL').success(function(data){ $scope.data = data; }); $.fullCalender({ data: $scope.data }); 你不能,你需

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

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

这是示例代码:

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

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

你不能,你需要通过承诺来应对,但你可以试着这样做:

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

$.fullCalender({
    data: $scope.data
});
但大多数人都会这么做

$http.get('URL').success(function(data){
    $.fullCalender({
        data: data
    });
});
如果FullCalendar对象不能处理异步数据,则可能需要将其包装为类似ng If的格式,或者在提供数据后强制重新绘制。您还可以使用路由解析强制控制器在数据加载之前不加载。

您可以使用此命令

以下是一个例子:

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

}
这是一个实用的答案,由将答案作为评论发布的用户提供。答案底部的实际使用示例

如果像我一样,您需要将该响应对象用作范围变量,这应该可以:

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

$scope.data = data;
$.fullCalender = $scope.data;
$scope.$apply()
});
$scope.$apply()
将持久化响应对象,以便您可以使用该数据

-

为什么需要这样做?

我一直在尝试为我的食谱应用程序创建一个“编辑”页面。 我需要用所选配方的数据填充我的表单。 在发出GET请求并将响应数据传递到$scope.form之后,我什么也没有得到<代码>$scope.$apply(),并在很大程度上发挥了作用。干杯,伙计

以下是我的editRecipeController中的示例:

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

希望有帮助

有没有办法避免这种情况?Javascript是单线程的,在等待响应时发出同步HTTP请求将阻塞整个浏览器。这不应该是您首选的解决方案。您是否可以简单地将对fullCalendar的调用移动到成功回调中,并将数据设置为等于回调的数据参数?当我在回调中使用fullCalendar数据时,它不会显示在模板上。日历不会触发的原因是,它不是在$digest循环中执行的。您必须将
$.fullCalendar….
放在成功回调中,然后调用
$scope.$apply()
,之后不返回由
$http
创建的承诺的原因是什么?将现有承诺包装为延期承诺是一种不好的做法,因为
$http
创建的承诺是异步的。我想知道为什么这会被接受为答案。OP问到同步,你回答了asynchronous@KingJulian是的,这不是答案$“then”块中的异步调用