如何在角JS同步HTTP请求 [英] how to make synchronous http request in angular js

查看:154
本文介绍了如何在角JS同步HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何阻断角JS HTTP请求,这样我可以使用的角度JS很下一行的$ HTTP响应。

在这里$ HTTP对象不返回的下一行的结果,这样我可以传递fullcalender JavaScript库的$ HTTP响应。

在这里scope.data $返回空值。

样code以下

  $ http.get(网址)。成功(功能(数据){$ scope.data =数据;});$ .fullCalender({
数据:$ scope.data
});


解决方案

您可以使用 的承诺为。

下面是一个例子:

  $ scope.myXhr =功能(){    变种推迟= $ q.defer();    $ HTTP({
        网址:'ajax.php,
        方法:POST,
        数据:POSTDATA,
        标题:{内容类型:应用程序/ x-WWW的形式urlen codeD'}
        })
        //如果请求成功
        .success(功能(数据,状态,头,配置){            //解决的承诺
            deferred.resolve(请求成功);        })
        //如果申请不成功
        .error(功能(数据,状态,头,配置){
            //拒绝承诺
            deferred.reject(错误);
        });    //返回的承诺
    返回deferred.promise;
}$ scope.callXhrAsynchronous =功能(){    变种myPromise = $ scope.myXhr();    //等到承诺回报的决心或退出
    //,然后有2个功能(resolveFunction,rejectFunction)
    myPromise.then(函数(解析){
        警报(解决);
        },功能(拒绝){
        警报(拒绝)
    });}

how to make blocking http request in angular js so that i can use the $http response on very next line in angular js.

here $http object doesn't return the result on next line so that i can pass the $http response on fullcalender a javascript library.

here $scope.data returns blank value.

Sample code below

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

$scope.data = data;

});

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

解决方案

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

}

这篇关于如何在角JS同步HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆