How can a Function expect the result of $http?

Asked

Viewed 261 times

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 post is saved on the server, I need to call the service UploadFileService to send an image or file to the server, sending the code so that the image or file can be linked with the respective publication.

The idea is to make the service call UploadFileService wait until $http returns with the post. I started messing with Javascript and Angularjs a little while ago and I’m having doubts about how to make chained Names (Synchronous requests), I read some posts in Portuguese and English but I don’t know how to use it to solve this problem.

If anyone can help, I’d appreciate it.

  • What problem are you having?

  • From what I understand, the $http makes an asynchronous call, which in theory allows the code to continue its execution until it finishes, right? The problem I imagine is this, it is possible somehow that the calls from the service UploadFileService are executed before the $http have received the response from the server? So far during my tests it has not occurred that the post will look like undefined and make a mistake, but I want to be able to prevent that from happening. I started reading about the papers a short time ago, so I still have doubts about how they work.

2 answers

5


The service $http 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 an 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 service $q in turn helps you perform functions asynchronously and use your return values (or exceptions) when they are processed.

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

However, the above explanation is valid only for versions that still implement the methods success and error, that analyzing the code entered in the question, is your case.

As well noted by @Onosendai, be aware that the methods success and error like callbacks of $http were declared discontinued. Instead, use the then passing as argument the functions of success and error.

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

    The use of Success and error made in this way, if memory serves, are for versions 1.4 down. The current versions it uses . then passing in parameter 2 functions that will be the callbacks of the Promise.

  • @Paulogustavo was what he put in the question, at least it is what is in the code, so I explained the reason of being used these 2 methods, what for me it made sense to explain.

2

Wait for the HTTP operation to return in a callback, that according to the $http service documentation must be included in the first parameter of the method then() 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 process cascading HTTP calls.

Observing: Do not use success and error as callbacks of $http. The documentation of 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.

Which translates as:

Notice of discontinuity

The methods of callback success and error [of the $http] service have been declared discontinued. Instead, use the default method. If $httpProvider.useLegacyPromiseExtensions is defined as false, then these methods will cast error $http/legacy.

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

Source: https://code.angularjs.org/1.5.9/docs/api/ng/service/$http

Browser other questions tagged

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