Nemesis19
Nemesis19

Reputation: 13

AngularJS service with $http.get doesn't pass data to a controller

I'm new to AngularJS and still stuck at the basics.

I'm creating a service with a $http.get to load a couple of Json files. When I load the service into the controller I get empty arrays.

This is my service

app.service('productService', ['$http', function($http){
    var lista = this;
    lista.products = [];
    lista.menu = [];

    $http.get('/prodotti_1.json').success(function(data){
        lista.products = data;
    });

    $http.get('/menu_1.json').success(function(data){
        lista.menu = data;
    });
}]);

And this is my controller:

app.controller('ProductController', ['productService', function(productService){
    console.log(productService.products);
    console.log(productService.menu);
}]);

The console prints just an empty Array [ ]. If I put the console.log(data) inside the success promise, the console.log prints the array just fine. I thought from codeschool it could be easier, but I guess I'm missing a point to pass the data from the success promise to the controller. In many other situations I see the usage of $scope variable, but I learnt that I can also avoid the use if I use "this". So that's my code doesn't display any $scope.

I'm using Angular 1.4.1 FYI and I saw many forums and other questions but it seems a different situation.

Thank you

Upvotes: 1

Views: 1373

Answers (1)

Pravin
Pravin

Reputation: 1701

You are accessing the variables before the promise is resolved. What you can do is return an object that has your various promises as property.

app.service('productService', ['$http', function($http){
    return {
         request1: $http.get('/prodotti_1.json'),
         request2: $http.get('/menu_1.json')
       }
}]);

So you can handle it in your controller.

app.controller('ProductController', ['productService', function(productService){
    productService.request1.success(function(data){
        //access the data
    });

    productService.request2.success(function(data){
        //access the data
    });
}]);

Hope it helps.

Upvotes: 1

Related Questions