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')}
}
});
});
Written by Miel Donkers
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Service
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#