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.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Kartik Tickoo
Kartik is a Full Stack Developer and has good experience in various technologies like HTML, CSS, Javascript, Advance Java and MySql.