Search code examples
javascriptangularjshttpangularjs-service

AngularJS $http request inside service


I'm trying to get some data from a Service into a Controller and I keep get an undefined variable.

angular
    .module("classes")
    .service("MyService", function ($http) {

        this.foo;
        $http.get("/classes/all").then(function (response) {
            this.fighters = response.data;
            this.foo = this.fighters;
            console.log(this.foo);
        });
        console.log(this.foo);

    })

When I run this I get on the console, by this order, line 11 is undefined and then line 9 returns me the array.

And when in the controller I try to get the variable foo, it also says undefined.

$scope.fooFighters = MyService.foo;

Solution

  • The reason is because of asynchronous execution of your API call. I would suggest you to rewrite the code to use a factory that will return a promise object. No need to bring unnecessary variables.

    angular.module("classes").factory("MyService", function($http) {
        return {
            fighters: function() {
                return $http.get("/classes/all").then(function(response) {
                    return response.data;
                });
            }
        }
    })
    

    And in your controller, you can get the value by injecting the service in the controller and then by referencing it like

     MyService.fighters().then(function(data){
       $scope.fooFighters = data;
      });