Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 504
N.Car Avatar asked Sep 21 '17 10:09

N.Car


People also ask

How do you modify the $HTTP request default Behaviour?

To add or overwrite these defaults, simply add or remove a property from these configuration objects. To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, e.g. $httpProvider. defaults.

Which AngularJS service is used to make the request to the server?

The AngularJS $http service makes a request to the server, and returns a response.

What is $HTTP in AngularJS?

$http is an AngularJS service for reading data from remote servers. The $http is a core AngularJS service that is used to communicate with the remote HTTP service via browser's XMLHttpRequest object or via JSONP.

How do we pass data and get data using http in angular?

Use the HttpClient.get() method to fetch data from a server. The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received. The return type varies based on the observe and responseType values that you pass to the call.


1 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;
  });
like image 169
Vivz Avatar answered Sep 28 '22 15:09

Vivz