简体   繁体   中英

Get Undefined from a variable

I have variable that assign from a service, and I need real time calculator from the variable's value to fill another variable.

Here's the code

$scope.getSubTotalSCTax = function(){
    TableService.checkOut('SubTotal',$scope.DetailMeja.finCheckInID)
    .then(function(response){
        console.log(response);
        $ionicLoading.hide();
        $scope.checkOut = {
            SubTotal:response.SubTotal,
            TaxPercentage:response.TaxPercentage,
            ServiceChargePercentage:response.SCPercentage,
        };
    }, function(err){
        console.log(err);
    })
};
$scope.getSubTotalSCTax();

$scope.checkOut.ServiceCharge = $scope.checkOut.SubTotal * $scope.checkOut.ServiceChargePercentage / 100;
$scope.checkOut.Tax = $scope.checkOut.SubTotal * $scope.checkOut.TaxPercentage / 100;

I always get error TypeError: Cannot read property 'SubTotal' of undefined at this line $scope.checkOut.ServiceCharge = $scope.checkOut.SubTotal * $scope.checkOut.ServiceChargePercentage / 100;

*EDIT : I'm have the input type="text" for the Tax Percentage and Service Charge Percentage. And I need to re-Calculate everytime the Tax Percentage Or Service Charge Percentage change their value

*EDIT2 : re-Calculate problem solved with ng-change event and call a function that run re-Calculate function

You need to account for the fact that TableService.checkout runs asynchronously. It won't have called the then callback until after the rest of your code has evaluated.

You can solve this by returning the promise.

$scope.getSubTotalSCTax = function(){
  var promise = TableService.checkOut('SubTotal',$scope.DetailMeja.finCheckInID);

  promise.then(function(response){
    // ...
  });

  return promise;
};

Then chaining another then onto the promise when you call the method.

$scope.getSubTotalSCTax().then(function() {
  $scope.checkOut.ServiceCharge = $scope.checkOut.SubTotal * $scope.checkOut.ServiceChargePercentage / 100;
  $scope.checkOut.Tax = $scope.checkOut.SubTotal * $scope.checkOut.TaxPercentage / 100;
});
scope.getSubTotalSCTax = function() {
    return TableService.checkOut('SubTotal', $scope.DetailMeja.finCheckInID)
};

$scope.getSubTotalSCTax().then(function(response) {
    console.log(response);
    $ionicLoading.hide();
    $scope.checkOut.ServiceCharge = response.SubTotal * response.SCPercentage / 100;
    $scope.checkOut.Tax = response.SubTotal * response.TaxPercentage / 100;

}, function(err) {
    console.log(err);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM