AngularJS $http request inside service

Viewed 6431

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;
2 Answers

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;
  });

because it will take some time to load the ajax/http request data after that line 9 will work. So if you want to work with ajax/http data then you should write code/function inside

$http.get("/classes/all").then(function (response) {
        // do something
    });
Related