angularjsangularjs-serviceangularjs-ng-resource

Angularjs: Store $resource data in service to share across controllers


Short question: Is it possible to store the data from $resource in a service, so as to query once and use it in different controllers?

I tried query().$promise.then, but still resource is returning an empty reference. What is the correct syntax to resolve and store the $resource data in a service, such that subsequent calls can make use of it?

factory('DataService', function($resource) {
    var resource = $resource("/api/data", {}, {
        query: { isArray: false }
    });

    var data;
    return {
        get: function (args) {
            if (!data) {
                resource.query().$promise.then(
                    function(result) {
                        data = result.message;  
                        return data;
                    }
                );  
            }
            return data;
        }
    }; 

Solution

  • Is it possible to store the data from $resource in a service, so as to query once and use it in different controllers?

    Yes, but I'd have it store the promise so then you've got a consistent API. For example

    .factory('DataService', function($resource) {
        // $resource definition here
    
        var promise;
    
        return {
            get: function() {
                if (!promise) {
                    promise = resource.query().$promise.then(function(result) {
                        return result.message;
                    });
                }
                return promise;
            }
        };
    })
    

    Then everything else can use

    DataService.get().then(function(message) {
        // do stuff with message
    })
    

    and it will only be retrieved once.

    You can create a new promise chain (using then) from the original promise as many times as you want and it will always resolve with the same, original result.message value