我有一个像这样的 $http.post
调用:
$scope.calcBarCost = function(bar, SAC, fieldSpeed) {
console.log('bar cost details', bar);
console.log('SAC', SAC);
console.log('FIELD SPEED', fieldSpeed);
data = {
SAC: SAC,
access_token: $scope.userData.access_token,
fieldSpeed: fieldSpeed
};
var barCost = 0;
return $http.post(apiPath + 'grabFieldLabor.php', data)
.success(function(response) {
var fieldLabor = 1000;
if(response.fieldLabor) {
console.log('Grab Field Labor Response', response);
// After we get the field labor then we can run the calculations
fieldLabor = parseFloat(response.fieldLabor);
console.log('FINAL FIELD LABOR', fieldLabor);
var averageCostPerHour = num($scope.userData.averageIronWorkersCost);
barCost = (bar.weight / (fieldLabor / 8)) * averageCostPerHour
var gradeCost = num($scope.costFactors[bar.grade]) * bar.weight;
var bendCost = num($scope.costFactors[bar.bend]) * bar.weight;
// Increased Cost Considerations
var cf = numberize($scope.costFactors);
var increasedCostConsiderations = 0;
increasedCostConsiderations += (percent(cf.weather) * barCost) + (percent(cf.difficultWorkspace) * barCost) + (percent(cf.materialLifting) * barCost) + (percent(cf.jobSiteInterferences) * barCost) + (percent(cf.naturalDisasters) * barCost) + (percent(cf.difficultCircumstances) * barCost);
barCost += gradeCost + bendCost + increasedCostConsiderations;
}
console.log('Final Bar Cost', barCost);
return barCost;
});
}
我试图返回检索数据后发生的计算,但数据没有返回。我做错了什么?
最佳答案
当您返回 $http.post 时,您实际上返回的是一个 Promise,而不是 .success 或 .then 函数中的返回值。
而不是
return barCost;
...在父范围内设置 barCost。
编辑:
选项 1( promise ):
function doSomePromiseRequests() {
return $http.post(...);
}
function parentFunction(){
doSomePromiseRequests().then(success, error);
}
function success(data) {
....
}
function error(data) {
....
}
选项 2(回调):
function doSomeRequest(callback) {
$http.post(...).then(function(success){
callback(success, null);
}, function(error){
callback(null, error);
});
}
function parentFunction(){
doSomeRequest(function(success, error){
...
});
}
编辑(在你扩展你的问题之后):
从 View / Controller 运行的函数:calculateBarCost。
$scope.calcBarCost 在发出 $http 请求后在 View 上更新。
$scope.calculateBarCost = function(bar, SAC, fieldSpeed) {
...
$http.post(apiPath + 'grabFieldLabor.php', data)
.success(function(response) {
....
$scope.calcBarCost = barCost;
});
}
关于javascript - 如何在 Angular JS 中返回 $http.post 的成功结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42098074/