service returning result of a $http

Asked

Viewed 1,474 times

1

I am creating a service for an application Angularjs where I should query a Ws and return a value to a variable. My problem is that when I use the $http I can’t get that amount back if I use a console.log()... I do so:

app.service('wsService', function($http){
  var callback;
  $http.get('http://www.meudominio.com/ws')
    .success(function (data) {
      callback = data;
    })
    .error(function (d, s) {
      callback = 'error';
    })
  ;
  //retorne o callback
  return callback;
});

my problem is that if I do this my job callback does not return the date or the error now if I give a console.log(data) within the .success or .error he returns...

how can I send the return of this request to the external variable?

  • 1

    Even creating a Global variable? var Valor; at the beginning and Value = date within the callback. Return Value

  • 1

    tries to declare callback within the .success and of .error, guy var callback = data;

  • @Diegosouza I create a global variable at the beginning of the service, it is defined there as callback but even so the return does not work...

  • @Caiofelipepereira try to do as you said, but if I declare internally I am creating a new variable but with its scope only inside the ajax... I had thought about it before but it didn’t work...

  • 1

    is that as ajax is asynchronous, it can cause this kind of problem. maybe set the global async as false resolve

  • @Caiofelipepereira could show me an example of where I configure this in Angularjs?

  • 1

    http://stackoverflow.com/questions/13088153/how-to-http-synchronous-call-with-angularjs take a look at this discussion. my suggestion, at the end of the day, is not that simple

Show 2 more comments

4 answers

1


My solution was to use the function $q Angular within my service. It instantiates a variable and sets a trigger for when there is a change of it, so I can pick up and do the $http with your return into my variable var defer = $q.defer() and when there is her change I continue my code.

(tip from Caio Felipe Pereira )

  • 1

    But the $http.get already returns a promise, no?

  • yes in the then() he returns, the problem is that the type of treatment I did depended on other status among the processes that occurred so I needed the $q

  • I’m glad it worked out. I had to wear a similar thing today and it worked fine

1

But it already returns a callback that can be returning from its service. The example Jonatas answered here is a better way to work.

When you run a $http it gives you some methods that are executed after the return is completed. Within your controller (or where to use the service) you will run and wait for its completion through the then method().

Example:

app.service('api', function($http){
    var api = {};
    api.busca = function(){
        return $http.get('....').then(function(data) {
            return data;
        });
    };
    return api;
});

And on the controller:

app.controller('testeCtrl', function($scope, api) {
    $scope.resultados = undefined;
    api.busca().then(function(data){
        // executado após a conclusão da execução
        $scope.resultados = data;
    });
});

This is one of the ways you can separate the responsibilities of each module.

  • yes correct, if I was sending the return to a controller. in my case I am using the $http within a service where his return goes to a second function within the service itself. As ajax is not synchronous he did not return what I need and the service gave error, so I used $q

  • 1

    @Leandroluk but you need the execution to be synchronous or just to run the methods in a chained way (one method calling another when finishing the processing)?

  • I needed the $http was completed and based on the data that he return me I do the treatment, therefore I need a synchronous solution. Not to mention that my result I would send to another function after treatment.

  • 1

    @Leandroluk but you do not need to be synchronous to perform a processing after the request is completed. The method then(), just as Success() or error() are executed only after the return of the $http.get() call. From there you can even pass this callback to another function

  • I know, my problem is that after the then() i was using another function that depended on the process. I was already using this method. Thank you for your commitment friend

1

Here I do something like this:

var variavel_global;
app.service('ajax', ['$http', function ($http){
    this.pesquisaCidade = function(q){
        return $http.get(url).then(function(response){
            return response;
        }, function(error){
            console.info('error: ' + error);
        });
    };
}]);
app.directive('pesquisa', ['ajax', function(ajax){
    return {
        link: function($scope){
            $scope.pesquisa = function (query){
                ajax.pesquisaCidade(query).then(function(resp){
                    console.info(resp);

                    //se quiser setar uma variavel
                    variavel_global = angular.copy(resp);
                });
            };
        }
    }
}]);

I think it gets more organized and easy to understand.

1

If it is information that you will use in global Scope, I recommend declaring the variable in global Scope, and within the function there assign value to it:

$scope.retorno;

and there in function:

$scope.retorno = error;

or

$scope.retorno = data;

Browser other questions tagged

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