Mr Myo Mr Myo - 6 months ago 16
AngularJS Question

how to merge two object array for angular js?

I am trying to merge two or more object arrays with angular js.

var app = angular.module('bookingApp', ['ui.bootstrap']);
app.filter('startFrom', function() {
return function(input, start) {
if(input) {
start = +start; //parse to int
return input.slice(start);
}
return [];
}
});

app.controller('bookingCtrl', function ($scope, $http, $timeout) {
$scope.init = function(){
$http({
method: 'get',
url: 'http://mmres.baganthandehotel.net/mmresadmin/invoicejson.php',
data: $.param({'search' : ''}),
headers: { 'Content-Type': 'application/json; charset=utf-8'}
})
.success(function(data){
var list1 = data;
angular.isObject(list1);
//console.log(list1);

});
$http({
method: 'get',
url: 'http://mmres.classique-inn.com/mmresadmin/invoicejson.php',
data: $.param({'search' : ''}),
headers: { 'Content-Type': 'application/json; charset=utf-8'}
})
.success(function(data){
var list2 = data;
//console.log(list2);

});
$scope.myConcatenatedData = list1.concat(list2);
console.log(myConcatenatedData);
};
});


I get two object arrays as list1 and list2 from two controllers.Now I want to merge list1 and list2 as an array. Please help me for this solution.

Answer

Wait for both HTTP requests to complete, then combine the lists. $http returns a promise, so you can use Promise.all (perhaps $q.all as this is Angular) to wait for them both to be done. See comments:

app.controller('bookingCtrl', function ($scope, $http, $timeout) {
    $scope.init = function(){
        var list1, list2;                    // Declare them here
        Promise.all([                        // Wait for both requests to complete (perhaps this should be $q.all)
           $http({
                  method: 'get',
                  url: 'http://mmres.baganthandehotel.net/mmresadmin/invoicejson.php',
                  data: $.param({'search' : ''}),
                  headers: { 'Content-Type': 'application/json; charset=utf-8'}
                })
            .success(function(data){
                list1 = data;
            }),
            $http({
                  method: 'get',
                  url: 'http://mmres.classique-inn.com/mmresadmin/invoicejson.php',
                  data: $.param({'search' : ''}),
                  headers: { 'Content-Type': 'application/json; charset=utf-8'}
                })
            .success(function(data){
                list2 = data;
            })
        ]).then(function() {                 // Then concat the lists
            $scope.myConcatenatedData = list1.concat(list2);
        });
    }; 
});