Как ждать, пока 2 $ http-запроса не прекратятся в angularjs - PullRequest
0 голосов
/ 25 сентября 2018

Мне нужно обработать ответы на два разных запроса $ http.Что является лучшим способом сделать это, зная, что я должен ждать ответов на оба запроса, прежде чем обрабатывать их результаты.Я думаю, что должен использовать что-то вроде асинхронного, обещания, ожидания функций, но я не могу понять, как это сделать.

var app = angular.module('Async', []);
app.controller('async', function($scope, $http, $timeout, $interval) {

    $scope.getCamionTypes = function() {
        $http.get("../services/getCamionTypes.php")
        .then(function mySucces(response) {
            $scope.camionTypes = response.data;
        }, function myError(response) {
            camionTypes = [];
        });
    } ;

    $scope.getParametres = function() {
        var b = $http.get("../services/getParametres.php")
        .then(function mySucces(response) {
            $scope.parametres = response.data;
        }, function myError(response) {
            $scope.parametres = [];
        });
    }

    //I make here the first call
    $scope.getCamionTypes();

    //I make here the second call
    $scope.getParametres();

    //The following instruction must wait for the end of the 2 calls
    console.log('Types de camion : ' + $scope.camionTypes + '\n' + 'Parametres : ' + $scope.parametres);

})

Ответы [ 3 ]

0 голосов
/ 25 сентября 2018

отметьте это

let promise1 = $http.get("../services/getParametres.php");
let promise2 = $http.get("../services/getParametres.php");

$q.all([promise1, promise2]).then(result=>{
 //console.log('Both promises have resolved', result);
})
0 голосов
/ 26 сентября 2018

Большое спасибо Самире и Шубхаму за вашу полезную помощь!Здесь код изменен благодаря вашим советам с меньшим влиянием на архитектуру моего приложения.С наилучшими пожеланиями.

var app = angular.module('Async', []);
app.controller('async', function($scope, $http, $timeout, $interval, $q) {

    $scope.getCamionTypes = function() {
        let promise = $http.get("https://www.alphox.fr/ModulPierres_dev/services/getCamionTypes.php")
        promise.then(function mySucces(response) {
            $scope.camionTypes = response.data;
        }, function myError(response) {
            camionTypes = [];
        });
        return promise;
    } ;

    $scope.getParametres = function() {
        let promise = $http.get("https://www.alphox.fr/ModulPierres_dev/services/getParametres.php")
        promise.then(function mySucces(response) {
            $scope.parametres = response.data;
        }, function myError(response) {
            $scope.parametres = [];
        });
        return promise;
    }

    //I make here the first call
    let promise1 = $scope.getCamionTypes();

    //I make here the second call
    let promise2 = $scope.getParametres();


    $q.all([promise1, promise2]).then (result=>{
        //The following instructions wait for the end of the 2 calls
        console.log('Types de camion : '); 
        console.log($scope.camionTypes);
        console.log('Parametres : ');
        console.log($scope.parametres);
        $scope.both = {camionTypes: $scope.camionTypes, parametres: $scope.parametres}
    });
});
0 голосов
/ 25 сентября 2018

Используйте Promise.all для таких случаев использования.Promise.all принимает массив обещаний и разрешается, когда оба обещания разрешены.Он потерпит неудачу, если любое из обещаний не выполнится.

$scope.getCamionTypes = function() {
    return $http.get("../services/getCamionTypes.php")
} ;

$scope.getParametres = function() {
    return $http.get("../services/getParametres.php")
}

Promise.all([$scope.getCamionTypes(), $scope.getParametres()]).then(resp => {
//resp[0] and resp[1] will contain data from two calls.
//do all your stuff here
}).catch()
...