I have an angular service that fetches data that will be used by multiple controllers. I only want to fetch the data from the db once and then have the service store the data in an object which controllers can reference through the service.

I'm using ui-router with multiple and nested views. Where should I put my service fetch so that my controllers can safely reference the data knowing the service fetched it successfully?

For example:

Where would I put this:

myAngularService.GetDbData(DataId).success(function (response) {
            this.myDbData = response;

So that in my controllers I can do this:

    controller('myCtrl', function($scope, myAngularService) {
        $scope.myDbData = myAngularService.myDbData;

I thought about using a resolve in my main state that houses all my other substates, however I'm not sure how to pass a parameter to my service that way (in this example the parameter would be DataId).

2 Answers 2


If you can cache the data for the lifetime of the page, put the call to GetDbData in the same location as your initialization for the page contents.

If you can't or don't want to cache the data, put it as close to the place where you will use it as possible.

Bear in mind that Ajax calls to external data can take some time to complete, making your user wait while it is happening.

  • But GetDbData is part of the initialization, so the question is where does the initialization go?
    – Legion
    Mar 23, 2016 at 13:30
  • That is going to depend entirely on your application, but at some point (whether through an included javascript file or directly) it has to go on the web page. Mar 23, 2016 at 14:43

A better way of achieving the required functionality will be to use $http's cache. Simply, convert the $http request to fetch data from db to be cachable.


$http.get(url, {cache: true});

This way, you can just inject and call the service's method in any controller you want and the get the cached data. The first $http request will get the data from db and cache it as well. The subsequent calls will return cached data.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.