简体   繁体   English

AngularJS-同步$ http.post请求

[英]AngularJS - Synchronous $http.post requests

I need to do two $http.post requests in my code. 我需要在代码中执行两个$ http.post请求。 The first one retrieve a key that is used by the second one for looking up a SQL database. 第一个检索键,第二个键用于查找SQL数据库。

At the moment, they're nested like this : 目前,它们像这样嵌套:

$http.post(...)
.success(function(data, status) {
    //Do something
    $http.post(...)
    .success(function(data, status) {
        //Do something else
    }
}

I highly doubt that this is the correct way of doing this. 我非常怀疑这是正确的方法。 Can't I make the second request wait for the first one, and end up with something like : 我不能让第二个请求等待第一个请求,结果却像:

$http.post(...)
.success(function(data, status) {
    //Do something
}

$http.post(...)
.success(function(data, status) {
    //Do something else
}

One of the great advantages of using the promise API os that you can stop nesting your callbacks, this allows for far more readable/maintainable code. 使用Promise API操作系统的巨大优势之一就是您可以停止嵌套回调,这使代码更具可读性/可维护性。

$http.post(...)
.then(function(result) {
    // do something
    return $http.post(...);
})
.then(function(result) {
    // do something with the second result
});

You should also note that the success/error way of dealing with a promise has been deprecated 您还应该注意,不赞成使用成功/错误方式处理承诺

The $http legacy promise methods success and error have been deprecated. $ http旧式的Promise方法成功和错误已被弃用。 Use the standard then method instead. 请改用标准然后方法。 If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error. 如果$ httpProvider.useLegacyPromiseExtensions设置为false,则这些方法将引发$ http / legacy错误。

https://docs.angularjs.org/api/ng/service/$http https://docs.angularjs.org/api/ng/service/$http

The first one is the safest way, as the calls are asynchronous and you can't guarantee the order of execution. 第一种是最安全的方法,因为调用是异步的,您不能保证执行的顺序。 As an alternative you can choose to have a flag in success block of first call, based on which you can fire up the second post call.. 或者,您可以选择在第一次调用的成功块中包含一个标志,根据该标志可以触发第二次调用。

With angular is the only way that you can do that, there are not synchronous ajax in angular. 使用angular是唯一可以做到这一点的方法,angular中没有同步ajax。 also this kind of method is better to separate them in different methods. 同样,这种方法最好将它们分离为不同的方法。

$http is an asynchronous api. $http是一个异步api。 However you can make them to behave like a synchronous call by using $q service. 但是,您可以使用$q服务使它们的行为类似于同步调用。

Here's an example demonstrating it. 这是一个演示它的示例。

Your first function 您的第一个功能

$scope.Func1= function () {
        var url= "http://stackoverflow.com";
        var query = "";
        var deferred = $q.defer();
        $http({
            url: url,
            method: "POST",
            data: query,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        })
        .then(function (response) {
            deferred.resolve(response.data);
        },
        function (response) {
            deferred.reject('failed');
        });
        return deferred.promise;
    };

Your second function 你的第二个功能

$scope.Func2= function (tmp) {
            var url= "http://stackoverflow.com";
            var query = "id="+tmp;
            $http({
                url: url,
                method: "POST",
                data: query,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            })
            .then(function (response) {
                // on success
            },
            function (response) {
                // on error
            });
        };

How to call them? 怎么称呼他们?

var promise = $scope.Func1();
    promise.then(function (resolve) {
        // this is called for deferred.resolve
        $scope.Func1(resolve); // calling second function
    },
    function (reject) {
        // this is called for deferred.reject
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM