Factory methods in multiple Angular JS files

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

One solution is to create 4 factories under the same module, each of which exposes one method in its own file. Then enter all of them into the controller that requires them.

Is there a better solution? I would like to create a Factory once and then add methods to it, as I did a module extension using a module template. Then I just need to enter Factory once and use all its methods.

+6
source share
3 answers

You can also organize vanilla js old-style code and then access these libraries in your services, for example:

var Mirko = { }; Mirko.FunService = { getAllSomething : function (p1, p2) { }, ... }; angular.module('myModule').factory('BigService', function(){ return { methodOne : Mirko.getAllSomething, ... }; }); 

As a result, you will have one Mirko object that you can access outside the scope of your angular application, but it is no different from other external api (not written for angular) that you would like to use in your application. The way you process your own โ€œexternalโ€ api can be done in the old fashioned way, in one file per โ€œclassโ€, for example. 'FunService'.

This may not be the most pleasant solution, but it will be a light abstraction.

Just say ...

+1
source

I would like to create a Factory once, and then add methods to it, as if I were doing a module extension using a module template. Then I just need to enter Factory once and use all its methods.

Yes, this 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 }; }]); 
+3
source

Perhaps segment your methods with other factories that can be introduced into your "main" factory:

 // file 1 angular.module('foo').factory('segment1', function () { return { method: function () { // ... super long method } }; }); // file 2 angular.module('foo').factory('segment2', function () { return { method: function () { // ... super long method } }; }); // your main factory file angular.module('foo').factory('myFactory', function (segment1, segment2) { return { method1: segment1.method, method2: segment2.method }; } 
0
source

Source: https://habr.com/ru/post/975353/


All Articles