2014-09-30 124 views
0

我有我想要“重新验证”的数据。所以我需要做一个get请求,保存回调中的数据,删除当前数据,然后用回调中的数据发表帖子。

我需要以某种方式使用$ q。

也许我完全没有,但这是我的尝试。

$scope.reSaveBIM = function(){ 

    var defer = $q.defer(); 

    defer.promise 
    .then(function(){ 
     $http.get('/api/bim/' + $scope.activePartOfBim._id) 
     .success(function(fullBIM){ 
      console.log(fullBIM); //Defined 
      return fullBIM; 
     } 
    ); 
    }) 
    .then(function(fullBIM){ 
     console.log(fullBIM); //Undefined 
     $http.delete('/api/bim/' + $scope.activePartOfBim._id); 
     return fullBIM 
    }) 
    .then(function(fullBIM){ 
     $http.post('/api/bim', {bim:JSON.stringify(fullBIM)}); 
    }); 

    defer.resolve() 

}; 

来自第一个回调的数据不会在链接中返回。我在正确的轨道上吗?我也尝试使用$ q.all,但失败了。

任何想法?

回答

1

没有必要创建一个额外的$q.defer对象,你可以简单地环比减少$http返回的承诺...

$scope.reSaveBIM = function() { 
    return $http.get('/api/bim/' + $scope.activePartOfBim._id).then(function(response) { 
     var fullBIM = response.data; 
     return fullBIM; 
    }).then(function(fullBIM) { 
     return $http.delete('/api/bim/' + $scope.activePartOfBim._id).then(function() { 
      return fullBIM; 
     }); 
    }).then(function(fullBIM) { 
     return $http.post('/api/bim', { bim:JSON.stringify(fullBIM) }).then(function() { 
      return fullBIM; 
     }); 
    }).catch(function(response) { 
     // return an error message using throw 
     throw "Something went wrong - Status " + response.status; 
    }); 
}; 

要叫它...

$scope.reSaveBIM().then(function(fullBIM) { 
    console.log('success! fullBIM: ', fullBIM); 
}, function(errorMsg) { 
    console.log(errorMsg); 
}); 
0

AngularJS的$ http已经包装了$ q服务。 From the documentation

$ http API基于$ q服务公开的延迟/承诺API。

基本上你的问题是$ http使用与你使用$ q创建的不同的承诺。你需要链接你的$ http调用来做同样的事情。事实是,您已经在使用$ q中的承诺。

此外,您可以通过声明函数并将它们作为变量传递,从而将其扁平化。

$http.get('/api/bim/' + $scope.activePartOfBim._id) 
    .success(firstSuccessFunction); 

var firstResponse; 
var firstSuccessFunction = function(fullBIM){ 
    console.log(fullBIM); //Defined 
    firstResponse= fullBIM; 
    $http.delete('/api/bim/' + $scope.activePartOfBim._id) 
      .success(secondSuccessFunction); 
}; 

var secondSuccessFunction = function(deleteResponse) { 
    $http.post('/api/bim', {bim:JSON.stringify(firstResponse)}); 
}; 
+0

当然,我可以建一个金字塔,但我想学习用承诺来平息它。 – Per 2014-09-30 16:54:18

+0

$ http已经对promises进行了操作。 .success()等同于.then()。如果你想平整你的代码,那么你不应该内联你的响应函数。尝试将函数作为参数传递给成功方法,即.success(mySuccessFunction); – 2014-09-30 16:58:48

+0

存在一个微妙的问题:'firstSuccessFunction'在传递给'.success(firstSuccessFunction)'时是'undefined'。 – 2014-09-30 19:22:04

0

你几乎是对的,你不需要defer。而不是success使用then。我认为成功不会回复承诺。另外$ http then成功回调有dataresponse.data属性。