Total Pageviews

2015/08/13

Promises in AngularJS

Problem
We would like to update the value which be marked by red rectangle in the following screenshot:


The value will be updated from 20 to 30:



After clicked save button, it will do search at once. The value seems does not be updated successfully, because the search result does not show the up-to-date value :

But as I click search button again, it show correct value.


original JavaScript code:
$scope.save = function(){            
    //do save
    fms426qService.save($scope.fms426qUpdateGridData);
    //do query
    $scope.query();
};


Solution
The root cause is the Javascript code had executed query before it finish its save action. Hence, you should make sure do query after save.

You can use Promises in AngularJS. The most powerful features of promises is the ability to chain them together. This allows the data to flow through the chain and be manipulated and mutated at each step. 

Therefore, you should update JavaScript code as bellows::
$scope.save = function(){            
    //do save
    fms426qService.save($scope.fms426qUpdateGridData).then(function(response) {
        //do query after save
        $scope.query();
    });
};


Reference
[1] http://andyshora.com/promises-angularjs-explained-as-cartoon.html
[2] https://thinkster.io/a-better-way-to-learn-angularjs/promises

No comments: