Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factory methods in multiple files Angular JS

What is the best practice when you have a Factory with like 4 related methods, each of those is really long (200+ lines of code) and you want to avoid having a huge file of 800+ lines of code?

One solution is to create 4 factories under the same module , each one exposing a single method and in its own file. Then inject all of them in the controller that requires them.

Is there a better solution? I'd like to create the Factory once, then add methods to it like I was doing module augmentation using the module pattern. Then I just need to inject the Factory once and have all its methods available.

like image 457
Mirko Avatar asked Sep 16 '14 12:09

Mirko


2 Answers

I'd like to create the Factory once, then add methods to it like I was doing module augmentation using the module pattern. Then I just need to inject the Factory once and have all its methods available.

Yes, that will work:

// In your main module file.
angular.module('myModule', []);


// file1.js
angular.module('myModule').factory('BigService1', function(){
    // Your actual implementation here.
    console.log('I am BigService1');
});


// file2.js
angular.module('myModule').factory('BigService2', function(){
    // Your actual implementation here.
    console.log('I am BigService2');
});


// ... additional files


// Separate file/service to aggregate your big factory services.
angular.module('myModule').service('AggregateService', [
        // Add dependencies
        'BigService1','BigService2',
function(BigService1, BigService2){
    // Return an object that exposes the factory interfaces.
    return {
        service1: BigService1,
        service2: BigService2
    };
}]);
like image 51
Sly_cardinal Avatar answered Oct 20 '22 18:10

Sly_cardinal


You could also arrange your code the old vanilla js style and then access those libraries in your services like this:

var Mirko = { };

Mirko.FunService = {
  getAllSomething : function (p1, p2) {
  },
  ...
};

angular.module('myModule').factory('BigService', function(){
  return {
    methodOne : Mirko.getAllSomething,
    ...
  };
});

You will end up with one object Mirko that you can access outside the scope of your angular app, but it will in no way differ from other externals api's (not written for angular) you would want to use in your app. The way you handle your own 'external' api can be done the oldschool fashion way, one file per 'class' e.g. 'FunService'.

It might not be the prettiest solution but it will be an easy abstraction.

Just saying...

like image 30
Per Hornshøj-Schierbeck Avatar answered Oct 20 '22 18:10

Per Hornshøj-Schierbeck