Decoupling the HTTP data fetching service from a Paging Component

I have various HTTP services that fetch data from the server.

I have a single paging component that I want to use in a number of views.

Therefore, I need a way to inject different services into my paging component for the fetchData() function to use.

Passing a String

The first time I attempted to do something similar I passed along the name of the service I wanted to inject from the controller to a directive. The directive had the $injector pull in the service based on the name.

angular.module('directives.firsttry', [])
  .controller('firstTryCtrl', function ($scope, $injector) {
    var theService = $injector.get($scope.serviceFactoryName);
    // do stuff with theService
})
/** 
 * @param {String} serviceFactoryName - The name of the service factory to be injected
 */
  .directive('firsttry', function() {
    return {
      templateUrl: 'firsttry.tpl.html',
      scope: {
        stateFactoryName: '@serviceFactoryName'
      },
      controller: 'firstTryCtrl'
    };
  });

There’s always a better way

For my recent paging component, I’ve created a fetch function that resolves to a request for data in the state definition for the view. Now, the function “dataProvider” can be passed to the controller and then the paging data source is instantiated with this function which I find to be a much more elegant solution.

dataProvider: function(HttpService) {
  return function(params) {
    return HttpService.getData(params);
  };
}

The params object is passed to the paging data source on instantiation- this allowed me to sanitize the incoming URL parameters prior to passing them on.

$scope.pagingdatasource = new PagingDataSource(params, dataProvider);

Lastly, when the paging data source fetches data it simply uses the params and dataProvider it was instantiated with:

this.fetchData = function () {
 dataProvider(this.params)
   .then(function(results) {
      // Do things with results
   });
};

It’s pretty nifty

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s