如何链接连续/连续$ http的角度?

时间:2014-10-03 21:09:56

标签: 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的示例,它们不涉及获取和使用响应。欢呼声。

1 个答案:

答案 0 :(得分:3)

这是要走的路:

$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(...)部分)时,将使用第二个promise的已解析值调用已链接的then()。另请注意return $q.reject(...)部分,这是流程进入第二个错误功能所必需的,而不是第二个成功函数。

相关问题