angularjs - 一个链如何连续/连续的 $http 以 Angular 发布?

标签 angularjs promise angular-promise

我对 AngularJS 还很陌生,并且正在不断学习。如何链接连续的 $http 帖子?我需要第一个 $http POST 的响应数据以在第二个 $http POST 中使用,其中我还需要第二个 POST 返回的响应。

$http({
    method: 'POST',
    url: 'http://yoururl.com/api',
    data: '{"field_1": "foo", "field_2": "bar"}',
    headers: {'Content-Type': 'application/json'}
}).then(function(resp) {

   $scope.data_needed = resp.data_needed;
    // Can't possibly do another $http post here using the data I need, AND get its reponse?
    // Would lead to a nested relationship, instead of adjacent chaining.

}, function(err) {
    // Handle error here.
});

我发现不能将另一个 $http 帖子与另一个 .then(function(resp) {}); 链接到最后一行代码。 ,出于同样的原因(请参阅上面代码块中的第一个注释)。

有什么建议吗?我似乎能找到的只是链接 $http GET 的示例,其中不涉及获取和使用响应。干杯。

最佳答案

这是要走的路:

$http({...})
    .then(
        function success1(response) {
            var data = response.data;
            $scope.xxx = data.xxx;
            return $http({...});
        },
        function error1(response) {
            return $q.reject(response);
        }
    )
    .then(
        function success2(response) {
            var data = response.data;
            $scope.yyy = data.yyy;
        },
        function error2(response) {
            // handle error
        }
    );

then() 函数返回一个 Promise(return $http(...) 部分)时,链接的 then() 被调用并返回第二个 Promise 的解析值。另请注意 return $q.reject(...) 部分,该部分是流程继续执行第二个 error 函数(而不是第二个 success 函数)所必需的。

关于angularjs - 一个链如何连续/连续的 $http 以 Angular 发布?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26186851/

相关文章:

javascript - 未捕获的对象错误 : can't inject ngAnimate

javascript - .callFake 与 $q 仍然不进入 .then block

angularjs - 如何在 AngularJS 中取消 $http 请求?

angularjs - 如何从ng-grid获取单元格值

javascript - Angular-formly:为什么指令的行为与类型不同?

javascript - 同步链接 Promise

javascript - 在类中的 promise 中回调?

AngularJS 应用程序在查询期间卡住

angularjs - 错误 11 秒后等待 Protractor 与页面同步超时

node.js - 事件触发时触发 Promise