Angular - modular definition of all services

Suppose I have service modules

// services/someService.js
export default function($q) {
  return $q.doSomething();
}

// services/anotherService.js
export default function($state) {
  return $state.doAnotherThing();
}

And I will say that I have a services index file

// services/index.js
import someService from 'someService';
import antoherService from 'anotherService';

export default {
  someService: someService,
  anotherService: anotherService,
}

In my angular module I want to be able to register them all (eloquently).

// awesomeModule.js
import services from './services';

angular.module('awesomeModule', [])
.services(services); // Want to emulate something like this

I'm having trouble finding a clean, clean way to register the index module so that I can prevent each service from registering separately in awesomeModule. Any way to do this?

* EDIT *

Using the @sdgluck clause, I created a utility function / module for registering arbitrary types of services with a module.

// utils.js
export function register(module, type, modules) {
  for (let extension in modules) {
    module[type](extension, modules[extension]);
  }
}

Inside my main module file, I turn on the utility and register these types of services.

// main.js
import {register} from './utils';
register(angular.module('awesomeModule'), 'service', services);
+4
source share
1 answer

"" Angular. , forEach, , .

, :

export default [
    { 
        name: "someService",
        fn: someService
    },
    { 
        name: "anotherService",
        fn: anotherService
    }
]

:

// awesomeModule.js
import services from './services';

let app = angular.module('awesomeModule', []);

services.forEach(({name, fn}) => app.service(name, fn));

, :

services.service('someService', services.someService);
services.service('anotherService', services.anotherService);
// and so on...
+3

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


All Articles