Jina Jina - 7 months ago 7
Javascript Question

merging two arrays from a service in angularJS

I have a problem in merging the Data from my web service that send the id of selected row in my table, and get with this id the data, this is what I get in console:

my all Liste [{ I get only the data of finalOperationsList not with the $scope.liste data}]


this is my code:

.factory('gammeMonatageFactory', function($http,$q){
var backObject = { getListOperationsById:_getListOperationsById }
return backObject;

function _getListOperationsById(val){
var defer = $q.defer();
$http({
method : "GET",
url : "MyURL/getById:"+val
}).then(function mySucces(response) {
defer.resolve(response.data);
}, function myError(response) {
deferred.reject('Erreur into url '+response);
});

return defer.promise;
};
});


and this is how I have called the service:

$scope.modifierOuCreerArticle = function() {
var v = $scope.OperationsList[$scope.OperationsList.length-1].Id;
gammeMonatageFactory.getListOperationsById(v).then(function(Data){
$scope.liste= JSON.parse(JSON.stringify(Data));
//I get the Data of $scope.liste only here I can't get this Data outside this call
});
$scope.listfinal = $scope.finalOperationsList.concat($scope.liste);
console.log("my all Liste "+$listfinal);
}


any help please to merge the 2
finalOperationsList
and
liste
arrays
thanks for help

Answer

When you merge the two array, the callback from the rest call wasn't executed yet. So, You should merge the two lists in your callback, when liste data is set. You can initialize the $scope.listfinal with an empty array or with some initial data. The view will update in consequence.

$scope.modifierOuCreerArticle = function() {    
     var v = $scope.OperationsList[$scope.OperationsList.length-1].Id;
     gammeMonatageFactory.getListOperationsById(v).then(function(Data){
         $scope.liste = JSON.parse(JSON.stringify(Data));  
         $scope.listfinal = $scope.finalOperationsList.concat($scope.liste); // concat the arrays when $scope.liste is available                         
     });
     $scope.listfinal = $scope.finalOperationsList; // or initialize the list with empty array;
     console.log("my all Liste " + $listfinal);
 }