on Writings, Tutorials, JavaScript, Angular, Code

Angular Services by example

This is a quick example to show how you can create a custom Angular service to limit the scope of another service. We'll create a service called 'GetData', which will limit the scope of Angular's $http, only exposing a certain method which can then be shared across an application. 

Why services? Angular offers services as a way to break code up into logical sections, allowing you to build components to be used in your application.

Services are dependency injected just like you would with $scope or $http - which are actually both services already provided by Angular. You can define your own service that could isolate certain functions of $http, only exposing the ones you need. We will do this in step 1 below:

Step 1: Create the service

        app.service('GetData', function ($http)){
            this.apiData = function(){
                return $http.get('/api/data')


Above, we create a new service, called ‘GetData’, and dependency inject $http. Then, we defined a function called ‘apiData’, which just returns the response of a $http.get().

Step 2: Use the service in a Controller

Now our service is defined, it can be used in other areas of our code, such as a controller:

app.controller(‘PostsCtrl’, function($scope, GetData){

        $scope.data = data

This time, in our controller, we dependency inject 'GetData', and then within the controller, we call the function we previously defined, apiData() which carries out the $http.get(). That's it - $http.get() has been nicely encapsulated.