angularjsangularjs-serviceangularjs-provider

how to create different versions of a service using angularjs providers


I have a function called itemService.. gets item from shoppingList controller and push it into items array then return this array back.

now i need to create 2 shoppingLists so using .factory i manged to make both controllers get different version of the service doing this code when i push an item through first controller the array for second controller won't get this item they are spattered now how can i do the same using .provider

function itemService (limit){
    let share = this;
    share.items=[];
    share.additem=function(N,Q){
        if(limit===undefined || limit>=share.items.length+1){
            let item={N,Q};
            share.items.push(item);
        }
        else {
            throw new Error("limit reached !")
        }  
    }
    share.getItems=function(){
        return share.items;
    }
}

function itemServiceFactory(){
    let factory = function(limit){
        return new itemService (limit);
    };
    return factory;
}

Solution

  • A factory, provider, service, and even value and constant are versions of the same thing. You can dissect the more general provider into all of them. Like so:1

    From version #1 of question:

    ERRONEOUS

    function itemServiceProvider(){
        let provider=this;
        provider.defaults={limit:10};
        // now i need to make 2 separated version of the service
        provider.$get = function(){
            return new itemService (provider.defaults.limit);
        };
    }
    

    To convert your factory to a provider:

    app.provider("MyProvider", function() {
        let provider=this;
        provider.defaults={limit:10};
        provider.$get = function() {
            return function(){
                return new itemService (provider.defaults.limit);
            };
        };
        return provider;
    });
    

    Usage:

    app.controller("cntl", function(MyProvider) {
         var service1 = MyProvider();
         var service2 = MyProvider();
    })
    

    Providers, Factories, and Services are singletons. The $get function is only invoked once during the life of an app. The provider.$get function needs to returns a function which constructs new services.

    For more information, see