Search code examples
angularjsmodulefactoryangularjs-service

How to break large Service Factory() into smaller blocks of code?


I am rather new to AngularJS and as I am writing my code, particularly my Services .factory()'s are getting quite large. As an example, in one factory I have 4 very large promises..and at the end I bundle them all into a $q.all([promise1(),promise2(),promise3(),promise4()]).then(function(response). It all works cleanly...however, as the factory grows and grows its getting harder and harder to managed each section of code.

I am looking a method that will allow me to clean up this giant .factory() and allow to me load the code into the factory from an external file OR break the .factory up but still be able to use $q.all(...) to have them all process at once...or some other method I am not thinking/aware of.

This is all for my own sanity in managing the code...as well as activating or deactivating specific promises by simply commenting out one line which in turn doesn't need to load all those bytes of code not being used.


Solution

  • Factories can be injected in factories. A large factory can be re-factored into smaller factories.

    app.factory("promiseService1", function() {
        return function promise1 () {
            var promise1;
            //code here
            return promise1;
        };
    });     
    
    app.factory("promiseService2", function() {
        return function promise2 () {
            var promise2;
            //code here
            return promise2;
        };
    });
    

    Then inject those factories into the top factory.

    app.factory("megaService", function($q, promiseService1, promiseService2) {
        return function megaPromise() {
            var promise1 = promiseService1();
            var promise2 = promiseService2();
            return $q.all([promise1, promise2]);
       }
    });
    

    In addition to making the code for the large factory more managable, the individual factories can be unit tested on their own.