2014-09-30 86 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屬性。