Angularjs $http.get

Asked

Viewed 2,417 times

0

Friends, I am new to Angularjs and I need your help.

Here’s the thing, I’m doing a request via $http Angularjs, I can get the data all right, but I need to do the post with the data I requested on $http.get().

Anyone who has ever needed to do this could help me? Thank you.

2 answers

2

Use inside the callback success of the 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 restorno from get on $scope and use it later when necessary.

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

    Thanks! I got it working!

0

What I would recommend in this case would be to use 2 separate functions. One for each $http that you need to do. This will give you more freedom, including in reusing the code.

Getting kind of 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 both through a function coming from the DOM:

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

and in the controller:

$scope.chamaHttp1 = http1();

Or reuse within the controller itself, following the same logic used in the function http1().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.