Oleksiy's Blog

Extending services in AngularJS


A good way to extend service for child module, is a good alternative for inheritance.

childModule.config(function($provide) {
      decorator('parentFactory', function($delegate, childFactory) {
        return _.compose(childFactory, $delegate);

$delegate represents returned value of factory that being decorated. This decoration will be available within a paricular childModule. I declared my factories as function returned and used Underscore.js _.compose() method which returns a function which applies function passed through arguments continuously (leftwards) to returned value of previous one. If I had worked with object returned factories, I would probably apply _.extend($delegate, childFactory)

Inheritance vs Decoration

Decoration is not inheritance, since after inheritance you have two instances, and after decoration only one.

That does NOT work if you're going to have more than one extension within a module. That practice restricts you to extract it into separate modules and cause module hierarchy overhead, so consider that in your design.

As a positive thing in that is making you design your application better and disallows you to use super-class directly from child's module by braking the Law of Demeter.

Anyhow, that way you manipulate your dependencies in declarative way on level of configuration, not implementation, which is good!