Giovanni Polì
Giovanni Polì

Reputation: 33

factory not working properly

I have an issue with a factory, it is called once the "HomeController" is called, the problem is that this also make a xhr request to an api, but the result seem to be cached or something, in a way when i go for the second time to the homecontroller, it doesn't make another request and it should. In fact the app console.log("HomeController") work perfectly an is called anytime i go in the homepage but the second console.log the ones inside the factory is called just once .

Here is the code:

app.controller("HomeController",function($scope,home_page,check_login,$rootScope){
    console.log("HomeController");

    $scope.home_json = {};

    home_page.success(function(data, status){
          $scope.home_json = data;
          console.log(data);
    });
});


app.factory('home_page', ['$http', function($http){
    console.log("/libs/home.php?date="+Date.now());
    return $http.get("/libs/home.php?date="+Date.now());        
}]);

Upvotes: 1

Views: 78

Answers (2)

Callum Linington
Callum Linington

Reputation: 14417

So Factories do act like singletons. So you are accessing the same instance each time. To change this behaviour:

app.factory('home_page', ['$http', function($http){
    var service = {
       getHome: getHome
    };

    return service;

    function getHome() {
        console.log("/libs/home.php?date="+Date.now());
        return $http.get("/libs/home.php?date="+Date.now());        
    }
}]);

This is now creating an object to be returned when the instance is called, it is the same instance each time. But now you can call a function on that object, getHome, which will execute that XHR request each time it is called.

Then the calling function is changed slightly:

home_page.getHome().success(function(data, status){
    $scope.home_json = data;
    console.log(data);
});

Notice the home_page.getHome(), so now your are calling the function on the object that is returned from the service.

Upvotes: 0

Pierre Gayvallet
Pierre Gayvallet

Reputation: 2953

Factories returns singletons. So this is actually the expected behaviour.

You should return an object exposing a method executing the ajax call instead of executing it during factory execution.

Upvotes: 1

Related Questions