Angularjs $ http.get

0

Friends, I'm new to AngularJS and I'm in need of your help.

This is the following, I'm doing a request via $http of AngularJS, I can get the data all right, but I need to do post with the data I requested in $http.get() .

Someone who has already had to do this could give me a hand? Thank you.

    
asked by anonymous 19.11.2015 / 03:46

2 answers

2

Use within the callback success of get:

$http.get("api/endpoint").success(function(data){
    // a partir daqui utilize a variável "data" em seu post
    $http({method:'POST', url:'api/endpoint2', data:data}).success(function(data){
        ...
    });
});

Another solution is to save the restore of the get to $scope and use it later when needed.

$http.get("api/endpoint").success(function(data){
   $scope.retornoDoGet = data; 
});
...
$http({method:'POST', url:'api/endpoint2', data:$scope.retornoDoGet}).success(function(data){
    ....
});
    
19.11.2015 / 03:55
0

What I would recommend in this case would be to use 2 separate functions. One for each% of% you need to do. This will give more freedom, including code reuse.

Getting more or less like this:

function http1() {
    return $http.get('seu/caminho/arquivo.json').then(
        function (response) { 
            outroHttp(response); 
        },
        function (err) { alert('Alerta de erro'); }
    );
};

function outroHttp(data) {
    return $http.post('seu/caminho/arquivo.php', data).then(
        function (response) {
            //Seu tratamento de dados aqui
        },
        function (err) { alert('Alerta de erro'); }
    );
};

In this way, you can call the function either through a function coming from the DOM:

<div ng-click="chamaHttp1()">Chama Função 01</div>

and no controller:

$scope.chamaHttp1 = http1();

Or reuse within the controller itself, following the same logic used in the $http function.

    
19.11.2015 / 12:12