Last Updated: February 25, 2016
·
3.557K
· mdonkers

Extending AngularJS services

AngularJS services can be extended (kinda) by injecting one service into another. You only need to make sure to use the correct object types for parameters and return values.

The below code shows how a 'basicCouchService' is extended by 'couchService'. Both input parameters are changed and the response is filtered.

myApp.factory('couchService', function (basicCouchService) {
    return {
        get: function(listType, response) {
            // Convert the input parameters to the schema-names used inside CouchDB
            var couchSchema = (listType.listType === 'latest') ? 'by_submit' : 'by_duration';
            basicCouchService.get({listType: couchSchema}, function (localResponse) {
                // Get the top-10, assume the array is already ordered wrong way around.
                var rowList = localResponse.rows;
                rowList = rowList.slice(rowList.length - 10, rowList.length);
                localResponse.rows = rowList;
                response(localResponse);
            });
        }
    };
});

myApp.factory('basicCouchService', function ($resource, $http, Base64) {
    return $resource('/mydb/_view/:listType',{
        listType: '@listType'
    }, {
        get: {
            method: 'GET',
            isArray: false,
            headers: {'Authorization': 'Basic ' +
                Base64.encode('username' + ':' + 'password')}
        }
    });
});