Это должно быть легко, но я не могу заставить его работать. У меня есть код ниже, который в основном извлекает данные с помощью $http
.
FYI Я использую POST, а не GET.
Прямо сейчас они работают параллельно. Можно закончить до другого. Моя цель - представить данные, как только все закончится. Поэтому я читал о $q
но я не могу заставить его работать.
$scope.getRestOpen = function () {
$http({
method: 'post',
url: "http://www.xxx.co.uk/php/xxx/restopen-get.php",
data: $.param({ 'location' : $scope.l,
'time' : $scope.t,
'day' : $scope.d,
'type' : 'get_restopen' }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.open = response.data.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.open = [];
});
}
$scope.getRestClosed = function () {
$http({
method: 'post',
url: "http://www.xxx.co.uk/php/xxx/restclosed-get.php",
data: $.param({ 'location' : $scope.l,
'time' : $scope.t,
'day' : $scope.d,
'type' : 'get_restclosed' }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.closed = response.data.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.closed = [];
});
}
Как вы можете видеть, я могу получить возвращенные данные из моих вызовов $http
в самой главной функции; $scope.closed = response.data.data;
и $scope.open = response.data.data;
Но я не хочу назначать их в $scope
только до тех пор, пока оба не закончатся. Поэтому я должен иметь возможность использовать $q
для выполнения ниже, но я не получаю данные в моей $scope
и никаких ошибок.
$q.all([$scope.getRestOpen, $scope.getRestClosed]).then(function(data){
$scope.open = data[0].data; // doesn't work
$scope.closed = data[1].data // doesn't work
});
Я делаю что-то неправильно?
Вам нужно, чтобы каждый элемент в $q.all()
возвращал обещание. Поскольку ничего не возвращается, ваш ответ будет [undefined, undefined]
.
Все, что вам нужно сделать, это заменить $scope.open = response.data.data;
с return response.data.data;
и он должен работать. Обязательно выполняйте то же самое в блоке catch.
EDIT: вот как должен выглядеть код
$scope.getRestOpen = function () {
return $http({
method: 'post',
url: "http://www.xxx.co.uk/php/xxx/restopen-get.php",
data: $.param({ 'location' : $scope.l,
'time' : $scope.t,
'day' : $scope.d,
'type' : 'get_restopen' }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
return response.data.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
return [];
});
}
$scope.getRestClosed = function () {
return $http({
method: 'post',
url: "http://www.xxx.co.uk/php/xxx/restclosed-get.php",
data: $.param({ 'location' : $scope.l,
'time' : $scope.t,
'day' : $scope.d,
'type' : 'get_restclosed' }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
return response.data.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
return [];
});
}
Измените свой код следующим образом
$scope.getRestOpen = function () {
return $http({
method: 'post',
url: "http://www.xxx.co.uk/php/xxx/restopen-get.php",
data: $.param({ 'location' : $scope.l,
'time' : $scope.t,
'day' : $scope.d,
'type' : 'get_restopen' }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
}
$scope.getRestClosed = function () {
return $http({
method: 'post',
url: "http://www.xxx.co.uk/php/xxx/restclosed-get.php",
data: $.param({ 'location' : $scope.l,
'time' : $scope.t,
'day' : $scope.d,
'type' : 'get_restclosed' }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
}
$q.all([$scope.getRestOpen(), $scope.getRestClosed()]).then(function(data){
$scope.open = data[0].data;
$scope.closed = data[1].data;
});
$scope.getRestOpen()
.
Посмотрите этот пример и прочитайте комментарий в коде:
var myApp = angular.module('myApp', []);
function MyCtrl($scope, $q, $timeout) {
var thenFn = function(value) {
console.log('resolved ', value);
return value;
},
q1 = $scope.q1 = $q.defer(),
q2 = $scope.q2 = $q.defer(),
p1 = $scope.q1.promise,
p2 = $scope.q2.promise;
//Wait complete all request
$q.all([
p1.then(thenFn),
p2.then(thenFn)
])
.then(function(values) {
$scope.fromThen = values;
});
// Must start the AngularJS digest process
// to allow $q.resolve() to work properly
// So use $timeOut() or $apply()
setTimeout(function() {
$scope.$apply(function() {
console.log('resolving delayed promises');
q1.resolve({
value: 1
});
q2.resolve({
value: 2
});
});
}, 100, this);
/*
* Alternative approach
*
$timeout( function() {
console.log('resolving delayed promises');
q1.resolve({value : 1});
q2.resolve({value : 2});
});
*/
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="MyCtrl">
{{fromThen}}
</div>
$q