0

There is a controller for each chart being displayed in application.

In a previous version, each controller made a separate server request to get data. But I want to combine these into a single request and share it among controllers.

So I've tried moving the request into a .run() block and then attaching response to $rootScope so all controllers can access it.

.run(['$rootScope', 'factoryName', function($rootScope, factoryName) {
    factoryName.getAll().success(function(data) {
        $rootScope.data = data;
    });
}])

The problem is its an asynchronous request, so controllers try to load the data from $rootScope before the response comes back from server, and crashes the app.

Normally I would use resolve from $stateProvider to get the response before state load, but the application just uses angular to make the front-end dynamic, and does not have multiple states, so I would like to avoid ui.router.

Is there a way to delay loading controllers until the response comes back?

2
  • Did you try using a promise? Commented Apr 29, 2016 at 4:17
  • Could you elaborate a little? Commented Apr 29, 2016 at 4:19

1 Answer 1

2

You can store the promise from the factory, and then chain from the promise to delay the functions that use the data.

.run(['$rootScope', 'factoryName', function($rootScope, factoryName) {
     //Store promise
     $rootScope.dataPromise = factoryName.getAll();
}])

In the controllers use the promise:

$rootScope.dataPromise.then(function onFulfilled(result) {
    var data = result.data;
    //Use data here
});

By using the .then method to queue a function with the $q service, the service will delay invoking the function, pending the arrival of the data.

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.