如何在Angular JS中返回$ http.post的成功结果

时间:2017-02-07 19:13:44

标签: javascript angularjs

我有$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;
  });

}

我正在尝试返回在检索数据后发生的计算,但数据未返回。我做错了什么?

3 个答案:

答案 0 :(得分:2)

当你返回$ http.post时,你实际上是从.success或.then函数中返回一个promise而不是返回值。

而不是

return barCost; 

...在父范围内设置barCost。

编辑:

选项1(承诺):

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){
       ...
    });
}

编辑(扩展您的问题后):

从您的视图/控制器运行的函数:calculateBarCost。
在$ http请求发生后,$ scope.calcBarCost在视图上更新。

$scope.calculateBarCost = function(bar, SAC, fieldSpeed) {

  ...

  $http.post(apiPath + 'grabFieldLabor.php', data)
  .success(function(response) {
     ....

    $scope.calcBarCost = barCost;
  });

}

答案 1 :(得分:0)

.success方法(deprecated and now removed from AngularJS 1.6) 忽略返回值。另一方面,.then方法使用返回值来创建一个新的派生promise,该promise将解析为返回的值。

$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) {
  //USE then method
  .then(function(response) {
    var data = response.data;
    var barCost;

    var fieldLabor = 1000;

    //...
    //Use data variable to calculate barCost
    //...    

    console.log('Final Bar Cost', barCost);

    return barCost;
  });

}

用法:

var barCostPromise = $scope.calcBarCost(bar, SAC, fieldSpeed);

barCostPromise
  .then( function(barCost) {
    console.log(barCost);
}).catch( function(errorResponse) {
    console.log(errorResponse.status);
});
  

你怎么回报价值?这需要在循环中运行几次

JavaScript是单线程的。函数只能返回一个立即可用的值或一个挂起承诺,该承诺稍后将使用服务器中的值(或根据服务器返回的值计算)来实现。

后续计算可以通过为promise的.then方法提供函数来完成。 .then方法提供的函数由$q Service保留,直到数据可用。

答案 2 :(得分:0)

您应该将promise-function function myFunction() { var age = document.getElementById("age").value; var favoritenumber = document.getElementById("favoritenumber").value; var birthdayyear = document.getElementById("birthdayyear").checked; var a1 = +(age - 10); var fn = +(favoritenumber * 2); var by; if (document.getElementById("birthdayyear").checked) { by = +14; } else { by = 0; } var total = +(a1 + fn + by); var table = document.getElementById("tableid"); var row = table.insertRow(0); var cella1 = row.insertCell(0); var cellfn = row.insertCell(1); var cellby = row.insertCell(2); cella1.innerHTML = a1; cellfn.innerHTML = fn; cellby.innerHTML = by; document.getElementById("submit").innerhtml = total; } 放在控制器中。类似的东西:

.success()