Basic Knowledge About AngularJs Services and Factories
AngularJs suggests Services and Factories to have global actions and variables for controllers and for many other AngularJs components. Gain a basic knowledge about AngularJs services and factories.
Why do we need AngularJs Services and Factories?
If you know something about AngularJS, maybe you know about MVC architecture and have heard about AngularJS controllers. But sometimes we need something global for all (or some) controllers, for example some functions or variables, or actions that help us communicate with the server side, etc. So what can we do now?
AngularJS wouldn't be so powerful if it didn't have its components to solve problems like these. AngularJS provides Services and Factories (sometimes Values and Constants) to have global actions and variables for controllers and for many other AngularJS components. Let's see how we can define a simple Service.
Services Code
angular.module('MyModule', [...])
.service('MyService', ['$http', function($http){
return {
users: [...],
getUserFriends: function(userId){
return $http({
method: 'GET',
url: '/api/user/friends/' + userId
});
},
deleteUserFriend: function(userId, friendId){
return $http({
method: 'DELETE',
url: '/api/user/delete/friend/' + userId +'/' + friendId
});
}
....
}
}])You can do the same thing using an AngularJS Factory. It works the same way, but instead of a constructor function, a factory is a function that returns an object. Now let's see how we can use that service. Let's define a simple controller and use that service.
AngularJs Controller Example
angular.module('MyModule')
.controller('MyController', ['$scope', 'MyService', function($scope, MyService){
$scope.users = MyService.users // some items inside array
$scope.deleteUserFriend = function(userId, friendId){
if(userId && friendId){
MyService.deleteUserFriend(userId, friendId)
.then(function(res){
// on success
})
.catch(function(res){
// on error
})
}
...
}
}])As you see, Services and Factories let us have service functions to communicate with the server, store data, etc.
AngularJS allows using Services and Factories inside other AngularJS components like Directives, Factories, or even inside other Services.