Angular Promises

0

I have on my controller:

$scope.test= function () {      
    var var1 = 0;
    var var2 = 0;

    var1 = TestService.loadVariable("1")
    var2 = TestService.loadVariable("2")

    $scope.result = var1 + var2;
}

and my service is:

    loadVariable : function(name) {
        return $http({
             method: 'GET',
             url: "/test/sheet/loadVariable/",
             params: {name: name},
            }).then(function success(response) {
                return response.data;
            }, function error(response) {

            });
    },

The problem is that I always get the result and I think it's because I do not have time to execute the loadvariables methods, any suggestions?

    
asked by sirdaiz 18.10.2017 в 17:16
source

1 answer

1

The problem you have is that since you are returning a promise, it will be invoked in the future, so when you do the sum it gives you "zero" because the promises have not been resolved.

To make it work for you, you must put everything in .then() and additionally start the second call to your service, to get the second value, and then do the addition and refresh the scope.

    $scope.test= function () {      
        var var1 = 0;
        var var2 = 0;

        TestService.loadVariable("1").then(function(response){
          var1 = resonse;
          TestService.loadVariable("2").then(function(response2){
             var2=resposne2
             $scope.result = var1 + var2;
           })
        })
}

I invite you to see this answer that I gave some time ago talking about this kind of problems

    
answered by 18.10.2017 / 17:53
source