Service Inheritance in AngularJS using ES6

One of the things that I’ve found is that my Angular services tend to have a lot of duplicate logic in them. The biggest culprit is HTTP calls for CRUD operations. Whether I’m using Restangular, ngResource, or plain ole’ $http, this has been a constant source of un-DRYing in my code. Let’s take a look at using ECMAScript 6’s class and extends to clean up this duplicate code.

We’ll first create a Base class, and put all our shared HTTP calls in there:

Then, we’ll make our individual services, and set them as subclasses that inherit from our Base class, using the new extends feature. In this example, we’ll create a service that represent ideas.

That’s pretty much the gist of it. If you’d like to see an example implementation, complete with routes and a controller, read on.

The next step is to create a routes file where we will resolve the HTTP query:

And then we inject our ideas into our controller:

And lastly, we import all our class files and load them into our Angular module as services and a controller:

That’s all folks! Got any ideas of ways I could make it better? I’d love to hear ’em.

  • Matthew Miller

    I noticed that you added BaseService as a service in the ideaLogger module. Based on my experience, that doesn’t actually contribute anything – importing the BaseService via relative path and then using “extends” to inherit is just typical ES6 inheritance.

    The hunt continues for something more “Angular-ic” in terms of implementing inheritance in an ES6 codebase…

    • http://www.ponderyourpath.com Aaron Gray

      You’re right, this is not “Angular-ic” inheritance – it is ES6 inheritance. But it seems to work well in my Angular apps to reduce code duplication, share functions, etc. What are the drawbacks you see with this approach? What are the benefits to something more “Angular-ic” in your view? 🙂

      • Matthew Miller

        Oh don’t get me wrong, ES6 inheritance has been working great, especially for services! My primary “issue” with it, though, is needing to relatively import the base service.

        I was hoping there’d be something within Angular that would let me “register” a BaseService globally as a “service-that-can-be-inherited”, but so far I haven’t found anything to that effect. Ideally I could do something like…

        import { BaseService } from ‘appModule/baseClasses’;

        …to get rid of that relative import.

        • http://www.ponderyourpath.com Aaron Gray

          Ahh, I see what you mean! Well please post back and let me know if you figure out if that’s possible. 🙂

Back