1

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.

0

1 Answer 1

5

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;
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.