How to create application specific services using AngularJS

Posted By : Kartik Tickoo | 30-Jun-2017

AngularJS implements "Separation of Concerns" using services architecture. Services are JS functions which are responsible to perform feature specific tasks only. This makes them an individual entity which can be easily maintained and tested. 

 

Controllers, filters can call them as on requirement basis. Services are normally injected using dependency injection mechanism of AngularJS.

 

There are many inbuilt services provided by AngularJS. All these services are responsible for a specific task. 

 

For example, $location, $https:, $route, $window, etc.

 

1. $https: is used to make ajax call to get the server data. 

2. $route is used to define the routing information and so on. 

3. Inbuilt services are always prefixed with $ symbol.

(function() {

    'use strict'

 

    app.factory('UserService', UserService);

UserService.$inject = ['sessionService','$http', '$timeout'];

function UserService(sessionService,$http, $timeout) {

return {}

}

}

 

UserService.linkClientToAdvisor(clientId, $scope.selectedAdvisor).then(function(result) {
            if (result.status === 200) {
                $uibModalInstance.close();
                toastr.success('Advisor Changed Successfully');
            } else {
                $scope.cancel();
                toastr.error('Advisor Change Unsuccessful');
            }
        }).catch(function(err) {
            $scope.cancel();
            toastr.error('Advisor Change Unsuccessful');
        });

 

 

Conclusion – 

In a nutshell, AngularJS services are substitutable objects that are wired together using dependency injection (DI). 

You can use services to organize and share code across your app.

Services are used for much more than mentioned here. To refer more, check out this blog by w3schools.

About Author

Author Image
Kartik Tickoo

Kartik is a Full Stack Developer and has good experience in various technologies like HTML, CSS, Javascript, Advance Java and MySql.

Request for Proposal

Name is required

Comment is required

Sending message..