Tutorial: Creating AngularJS Services

Imagine that you have a project with countless features responsible for performing a huge variety of tasks, if you don’t do as much as you can to organize it, how would the code look like? It would be nearly impossible to maintain this project if everything is mixed together in the code, no one would understand it. To make things easier we make whatever we can to keep our code as readable and clean as possible, and that’s what AngularJS Services are good for.

Let’s suppose your project has a lot of features related to products management, you wouldn’t put that together with the code related to employees management, right? Of course not, they have nothing to do with each other, in this case AngularJS allows you to create a service for products and another one for employees, this way all the business logic would be organized in its appropriate service. If someone in the future needs to develop a new product related feature, he/she will know where to find the business logic related to it.

Now let’s see how that looks like in code, I’m going to create 2 services (productService and employeeService), each one will have it’s specific functions, which of course will be different from each other, the productService will allow us to get information and check the availability of an specific product, as the employeeService will only have a function to update the employee profile.

At this point, if you still don’t have an AngularJS module declared just declare one with a name of your choice, I’m going to use ‘angularjsServicesExample':

var app = angular.module('angularjsServicesExample',[]);

With our module created we can now start adding services to it:

app.service('productService', function($http, $q){
    this.isAvailable = function(productId){
        console.log('productService.isAvailable called!!');
    }
    this.getInfo = function(){
        console.log('productService.getInfo called!!');
    }
});
 
app.service('employeeService', function($http, $q){
    this.updateProfile = function(newInfo){
        console.log('employeeService.updateProfile called!!');
    }
});

Really simple, right? But how do we use these services? Using them is even easier, you just need to add them to your controller, then you can just call your functions:

app.controller('myController', function($scope, productService, employeeService){
    productService.isAvailable('1');
    productService.getInfo();
    employeeService.updateProfile('test');
});

That’s it!! If you run your project you’ll see the texts printed on the console.

Thanks for reading this tutorial, hope it was helpful for you, if you have any doubt just leave a comment.
Till the next one!!

Recommended for you

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>