Angular - modularly define all services

Seth

Say I have service modules like so

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

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

And say 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 all of them (eloquently).

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

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

I'm having troubling finding a nice clean way to register the index module so that I can prevent registering each service individually in the awesomeModule. Any way to do this?

* EDIT *

Using @sdgluck's suggestion I created a utility function/module to register arbitrary service types with a module.

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

Inside of my main module file, I include the utility and register service types like so.

// main.js
import {register} from './utils';
register(angular.module('awesomeModule'), 'service', services);
sdgluck

You cannot 'batch' register modules in Angular. However using forEach, arrow functions, and destructuring you can quite cleanly register each of the imports on a single line.

First restructure how you export the services to the following array of objects pattern:

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

Then use the export like this:

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

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

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

This would yield the same result as if you were to do the following:

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related