Thursday, October 29, 2015

Angular 1.x services as ES6 classes

Following up on my post of an angular 1.x directive implemented as an ES6 class, I worked up a pattern for services.  It's even simpler than the directive, in that the service has no link function to worry about.

I still make an initClass() method that describes the constructor parameters that need to be injected, but note that the factory method only injects an $injector that it uses to create the service.  As with anything, there are many different ways you can do this.  At the end I'll show you a more brief way to do this.

import 'angular';
/*
 * Angular service as a class
 */
export class DataService {
    static initClass() {
        DataService .$inject = ['$resource', '$q'];
    }

    constructor($resource, $q) {
        this.$resoure = $resource;
        this.$q = $q;
        this.latest = $resource('/data/latest/:name');
        this.tables = $resource('/data/config/default_table');
        this.tags = $resource('/data/tags', {},
            {get: {method: 'GET', isArray: true}});
    }

    getLatestValue(key) {
        var deferred = this.$q.defer();

        this.latest.get({"name": key}).$promise.then( (result) => {
            deferred.resolve(angular.fromJson(angular.toJson(result)));
        }, (error) => {
            deferred.reject(error);
        });

        return deferred.promise;
    }

    getTableConfig() {
        var deferred = this.$q.defer();

        this.tables.get().$promise.then((result) => {
            deferred.resolve(angular.fromJson(angular.toJson(result)));
        }, (error) => {
            deferred.reject(error);
        });

        return deferred.promise;
    }

    getAllTags() {
        var defer = this.$q.defer();
        /* This is an example of how to cache the result */
        if (angular.isDefined(this.tag_cache)) {
            /* Resolve from the cache */
            defer.resolve(tag_cache);
        } else {
            /* Not cached, so resolve from the backend server */
            tags.get().$promise.then( (allTags) => {
                this.tag_cache = {};
                alltags = angular.fromJson(angular.toJson(allTags));
                angular.forEach(allTags, function (t) {
                    tag_cache[t.name] = t;
                });
                defer.resolve(tag_cache);
            }, (error) => {
                defer.reject(error);
            });
        }

        return defer.promise;
    }


    static register(module) {
        module.factory('dataservice', [ '$injector', function($injector) {
            return $injector.instantiate(DataService);
        }]);
    }
}

If you're not like me (and you don't care about having the injectables defined in the source close to the constructor) you can skip initClass() and setting up DataService.$inject and just set them when you call instantiate():

    static register(module) {
        module.factory('dataservice', [ '$injector', function($injector) {
            return $injector.instantiate(DataService, [ '$q', '$resource' ] );
        }]);
    }


Back in app.js you do just as before:

import { DataService } from 'services/dataservice';
...
DataService.register(mainModule);
...

I'm doing all of this with System.js but it's on my short list to try it all with webpack.  I will let you know when that works.

By the way .. if you're wondering what all this fromJson(toJson()) stuff is: the object that comes back from $resource has some extra items in it (beyond what the server returns).  That's the recommend trick for stripping them out.  It's not really necessary to strip them out - in particular, if you use ngResource to POST them back it strips things like $promise out before POSTing.  Again, though, I'm a little OCD about this, especially if I display the raw result using the angular json $filter, so I take the trouble to clean up the object.  It's an optional step.


Wednesday, October 28, 2015

Angular Directives as ES6 Classes

I have been working on having my angular 1.x directive's controllers exist as classes, just like I already do with pure controllers and with services.  I'm honing in on a pattern for directives that I like.

This accomplishes is a few things:
  • Consolidating the directive into a single class reduces global namespace and scope pollution.
  • When you use an ES6 loader (like System.js or webpack) there's just one thing to export/import: the class itself
  • app.js still has to call a registration function, but it's now simpler.  It calls a static class method with one parameter, the module to which to attach the directive.  No longer does app.js have to know what parameters to inject into some directive that's off in a separate file.
  • Writing your controllers as classes encourages you to write directive logic in more testable ways.  Hiding the call to angular's own directive registration keep's the class's business private.  I have found that doing this helps me clarify what's done in the controller vs. the link function, and thinking about that has made my link functions very short (as I think they should be).
  • I still provided a way to hook in to the directive lifecycle to do things like cancel timers, in-process requests to ngResource, etc.

So for the pattern looks like this:

/*
 * A directive called "Reformer", in a Class
 */
export class Reformer{

   static inject() {  Reformer.$inject = [ '$interval', '$q' ];  }
   constructor($interval, $q) {
      this.$interval = $interval;
      this.$q = $q;
   }
   
   tick() {
      console.write("Ping!");
   }

   initialize() {
      this.timer = this.$interval( () => { this.tick() }, 1000);
   }

   destroy() {
      this.$interval.cancel( this.timer );
   }


   static register(module) {
      module.directive('reformer', function () {
         return {
            restrict: 'E',
            templateUrl: 'reformerTemplate.html',
            transclude: false,
            replace: true,
            scope: false,
            controller: Reformer,
            link: function (scope, elem, attrs, ctrl) {
               ctrl.initialize();

               scope.$on('destroy', function () {
                  ctrl.destroy();
                });
             }
          };
      });
   }
}
Reformer.inject();  /* set up injection */

Now, from app.js you just call the static registration method:

import { Reformer } from 'reformer';
Reformer.register(mainModule);


If you're wondering why I did the $inject spec that way, it's because it drives me nuts to have the constructor at one end and the $inject spec at the other end of the file.

This same basic technique works with services, but since they are a little simpler I did not document them here.