【问题标题】:How does one chain successive/consecutive $http posts in angular?一个链连续/连续的 $http 如何以角度发布?
【发布时间】:2014-10-04 06:01:51
【问题描述】:

我对 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 的示例,这些示例不涉及获取和使用响应。干杯。

【问题讨论】:

标签: angularjs promise angular-promise


【解决方案1】:

这是要走的路:

$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 函数而不是第二个成功函数所必需的部分。

【讨论】:

  • 谢谢,这行得通!现在我只需要弄清楚如何正确表达 http 标头 -H "Authorization: JWT <your_token>" 角度...再次感谢!
猜你喜欢
  • 2016-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多