3

I use the following factory to fetch data from API and store it to local variable called apiData.

app.factory('MyFactory', function($resource, $q) {

    var apiData = [];
    var service = {};

    var resource = $resource('http://example.com/api/sampledata/');

    service.getApiData=function() {
        var itemsDefer=$q.defer();
        if(apiData.length >0) {
            itemsDefer.resolve(apiData);
        }
        else
        {
            resource.query({},function(data) {
                apiData=data;
                itemsDefer.resolve(data)
            });
        }
        return itemsDefer.promise;
    };

    service.add=function(newItem){
        if(apiData.length > 0){
            apiData.push(newItem);
        }
    };

    service.remove=function(itemToRemove){
        if(apiData.length > 0){
            apiData.splice(apiData.indexOf(itemToRemove), 1);
        }
    };

    return service;

});

I inject the apiData into my controllers the following way:

 $routeProvider
    .when('/myview', {
        templateUrl: 'views/myview.html',
        controller: 'MyController',
        resolve: {
            queryset: function(MyFactory){
                return MyFactory.getApiData();
            }
        }
    })

app.controller('MyController', ['$scope', 'queryset',
    function ($scope, queryset) {
        $scope.queryset = queryset;
    }
]);

Is it a good way to share a promise between different controllers or I better to use local storage or even cacheFactory?

How can I rewrite MyFactory add() and remove() methods so that I can keep my shared variable in a current state (no API update/create/delete calls needed)?

Thank you!

1

1 Answer 1

0

You should use $resource to get $promise eg: resource.query().$promise instead of $q.defer() for cleaner code. Otherwise you are good to go. You could use $cacheFactory, but you can also use local var.

Isn't your shared variable in a current state with current code?

I recommend you take a look at ui-router and its nested and abstract views, where resolved values are available to child controllers.

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.