Я пытаюсь объединить два или более объектных массива с угловыми 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);
};
});
Я получаю два массива объектов как list1 и list2 из двух контроллеров. Теперь я хочу объединить list1 и list2 в качестве массива. Пожалуйста, помогите мне в этом решении.
Подождите, пока оба HTTP-запроса будут завершены, а затем объедините списки. $http
возвращает обещание, поэтому вы можете использовать Promise.all
(возможно, $q.all
как это $q.all
), чтобы ждать их обоих. См. Комментарии:
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);
});
};
});
result = []
( result = []
), а затем серию push
вызовов: result.push.apply(result, arr1); result.push.apply(result, arr2); result.push.apply(result, arr3);
(вероятно, в цикле). (В ES2015 это было бы намного красивее: result.push(...arr1); result.push(...arr2);
) Если вы спрашиваете о серии запросов $http
, создайте массив их возврата). значения (их обещания), а затем передать этот массив $q.all
(или Promise.all
). Это будет ждать их всех.
Вызовите второй запрос $http
в обработчике успеха первого $http
.
Поскольку ajax
является асинхронным по своей природе, к моменту применения .concat
обе переменные не undefined
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(data1) {
$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(data2) {
$scope.myConcatenatedData = data1.concat(data2);
console.log(myConcatenatedData);
});
});
};
});
Изменение: Как предложил великий TJ Crowder, нет необходимости откладывать вызов второго запроса $http
поэтому $q.all
можно использовать или Promise
как объяснялось в его ответе.
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() {
$q.all([$http({
method: 'get',
url: 'http://mmres.baganthandehotel.net/mmresadmin/invoicejson.php',
data: $.param({
'search': ''
}),
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}),
$http({
method: 'get',
url: 'http://mmres.classique-inn.com/mmresadmin/invoicejson.php',
data: $.param({
'search': ''
}),
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
})
]).then(function(response) {
$scope.myConcatenatedData = response[0].concat(response[1]);
console.log(myConcatenatedData);
})
};
});
$q.all
но, как обычно, ты получил первый :)
console.log
? Я думаю, что это дает неопределенный, так что вы, вероятно, должны вложить свой второй http-запрос в случае успеха первого и concat в случае успеха второго