How do I make a function wait for the $ http result?

5

I'm having trouble with the following code:

$http({
    method: 'POST',
    url: '/publicacao/',
    data: $scope.publicacao,
    headers: {'Content-Type': 'application/json'}
}).success(function(publicacao) {
    $scope.publicacao = publicacao.data;
    console.log($scope.publicacao);

    //Upload de imagem
    if ($scope.tipo == 'imagem') {
        var arquivo = $("#imagem")[0].files[0];
        var nomeArquivo = $("#imagem")[0].files[0].name;

        UploadFileService.uploadArquivo('/upload', arquivo, nomeArquivo , publicacao.codigoPubl , 'imagem');
    }

    //Upload de arquivo
    else if ($scope.tipo == 'arquivo') {
        var arquivo = $("#arquivo")[0].files[0];
        var nomeArquivo = $("#arquivo")[0].files[0].name;

        UploadFileService.uploadArquivo('/upload', arquivo, nomeArquivo , publicacao.codigoPubl , 'arquivo');
    }

    $location.path('/timelines/' + $routeParams.codTime);
    $window.location.reload();
    $scope.addSucessoMsg();
}).error (function(erro) {
    console.log('Erro ao adicionar a publicação: ' + erro);
    $scope.addErroMsg();
});

After the publication is saved on the server, I need to call the UploadFileService service to send an image or a file to the server, sending the code so that the image or file can be linked to its publication.

The idea is to make the service call UploadFileService wait until the $ http returns with the publication. I started messing with JavaScript and AngularJS recently and I am not sure how to do chained promises (

asked by anonymous 29.01.2017 / 21:29

2 answers

5
The $http service is a function that takes a single argument - a configuration object - that is used to generate an HTTP request and returns a promise ( source code ).

$http({
    //objeto de configuração
})
//...

However, it uses an abstraction of $q ( documentation ) and because it is a abstraction it renames the callback functions. Instead of .then and .catch is .success and .error .

$http({
    //objeto de configuração
}).success(function(data) {
    //requisição HTTP executada com sucesso
}).error (function(error) {
    //algo correu mal
});

The $q service in turn helps you perform functions asynchronously and use their return values (or exceptions) when they are processed.

That is, everything within the callback function defined in the .success method will execute after the completion of the HTTP request, if it is executed successfully, otherwise the callback function defined in the .error .

However, the above explanation is valid only for versions that still implement the success and error methods, which, if you analyze the code inserted in the question, is the case.

As noted by @ OnoSendai , note that the success and error methods as callbacks of $http have been declared discontinued. Instead, use the then method by passing the success and error functions as an argument.

$http({
     //objeto de configuração
}).then(function successCallback(response) {
    //requisição HTTP executada com sucesso
}, function errorCallback(response) {
    //ocorreu um erro
});
    
29.01.2017 / 22:25
2

Wait for return HTTP operation in a function callback , which with the service documentation $ http should be present in the first parameter of the% object_ method of the returned object:

$http({
  method: 'GET',
  url: '/umaUrlQualquer'
}).then(function successCallback(response) {

    // este callback é chamado assincronamente
    // quanto a resposta está disponível

  }, function errorCallback(response) {

    // chamado assincronamente quando um erro ocorre,
    // ou quando o servidor responde com um código de erro.

  });

If necessary, use chain promises to handle HTTP calls cascading .

Note: Do not use then() and success as callbacks of error . The documentation for version 1.5.9 has the following announcement:

  

Deprecation Notice

     
    

The $ http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $ httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $ http / legacy error.

  

That translates as:

  

Discontinuity warning

     
    

The methods of callback $http and success [of the $ http service] have been declared discontinued. Instead, use the default method. If error is set to $httpProvider.useLegacyPromiseExtensions , then those methods will throw the false error.

  

Version 1.6.0 no longer includes the news, which makes me believe that the methods have been removed.

Source: link

    
30.01.2017 / 16:01