user3648646
user3648646

Reputation: 711

How do I get my angularjs factory to only fetch http data one time?

I am using a factory to share data between multiple controllers, here is my factory

    var szGetData = "some url that works";
    myApp.factory('Data', function ($http) {
        var eventData = {};
        eventData.getEvent = function (event) {
                return $http.get(szGetData, event);
            }
        return eventData;
    });

In my controllers I call the factory the same way for each one as follows:

        Data.getEvent()
            .success(function (event) {
                $scope.eventData = event;

            })
            .error(function (error) {
                $scope.status = 'Unable to load customer data: ' + error.message;
            });

This all works and I get the data but it calls my web-service three times and each controller has its own copy of the data. I would like to have the controllers working of the same data and only call the web-service once. thanks for your suggestions.

Upvotes: 1

Views: 864

Answers (1)

TheSharpieOne
TheSharpieOne

Reputation: 25726

You can keep track of the pending promise and return the same promise to all of the subsequent callers.

Optionally, if the request fails, you can "reset" the promise so that the next time getEvent is called (after it failed) it will try again.

var szGetData = "some url that works";
myApp.factory('Data', function ($http) {
    var eventData = {};
    var promise;
    eventData.getEvent = function (event) {
        if(!promise){
            promise = $http.get(szGetData, event)
                .error(function(){ // this is optional
                    promise = false;
                });
        }
        return promise;
    }
    return eventData;
});

Upvotes: 5

Related Questions