I
I
imelos2015-10-20 13:44:24
Angular
imelos, 2015-10-20 13:44:24

Requesting data in a multi-controller factory?

There is a simple data sharing between controllers

.factory('Games', function () {
        var games = {
                 list: []
            }
        return {
            get: getGames,
            set: setGames,
        };

        function getGames() {
            return games;
        }
        function setGames(gamesList) {
            games.list = gamesList;
        }
 })

Further controllers use this factory to take data
.controller('MyCtrl1', function($scope,Games){
        $scope.games = Games.get()   
    });
 .controller('MyCtrl2', function($scope,Games){
        $scope.games = Games.get()   
    });
и так далее

I get the data from the request API. Accordingly, I look in the controllers
.controller('MyCtrl1', function($scope,Games,$http){
        $scope.games = Games.get()
        // если нету данных в фабрике - запросить их и засетить
        if (!$scope.games.list.length) {
            $http(....).then(function(response)) {
                 Games.set(response.data)
             }
        }
    });

And so in all controllers.
Because of this, a problem arises, if I have several such controllers on the page, then they all simultaneously request data.
How to solve this problem? Is it possible to query the data in the factory? What is the best way to organize it so that everything can be done with one request to the server.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lega, 2015-10-20
@imelos

The factory should request data from the server, for example, when creating (if the data does not change during operation), the factory creates a "singleton" so the loader at the start will be executed only 1 time.
If you need to get data in the controller, but there is none in the factory yet, then getGames should be asynchronous (for example, return a Promise).
If the data changes over time and the controller needs to respond to it, then you can do something like the factory sent out a pubsub message about the new data, and the controllers reacted to this and requested Games.get () again.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question