angularjs .service() simple mixin approach

We are developing angularjs .services() which have significant common behavior. We want to reuse that code and js inheritance and mixins are options to do that.
There are articles out there about this, heres a good one for .factory() which defines a function constructor and more on stack overflow as well as this good post.

I took a mixin approach and implemented as follows:

    ChildService.$inject = [
    'ParentService'
    ];

    /**
     * Service constructor
     */
    function ChildService(
            ParentService) {

        // mixin from parent using angular.copy
        // note: using copy because angular.extend() does not safely mixin non primitive properties
        angular.copy(ParentService, this);

        this. doSomething = doSomething;

        // local methods (some private, some public)
        function doSomething(params) {
        }
    }

I'm copying methods and properties from ParentService to ChildService.
This is only suitable for .service() services, not .factory() services because services created with .service() are singletons so using prototypal inheritance does not gain us anything (imo).
I also like that I can define and inject ParentService just like a normal angular service.

Is prototypal inheritance better than this mixin approach?
- Maybe, I would also like to refactor to use prototypal inheritance to compare and contrast.
- Another consideration is if I needed to inherit from more than one Parent then a mixin approach would be necessary. So good to know how to approach it.

note: I used angular.copy() instead of angular.extend() because angular .extend() does a shallow copy and my ParentService had non primitive data properties I wanted to mixin and had to be deep copied. I plan to migrate to angular.merge() which is available in angular 1.4 which we are currently upgrading to. Another option which works is to use jquery $.extend passing true to do a deep copy.

On a side note we have found jquery copy is much much faster than angular.copy when dealing with large data sets.

Comments

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

react-router v6.4+ loaders, actions, forms and more