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 as global for all (or some) controllers, for example some functions, or variables, actions which will help us to communicate with server side, etc...So what can we do now?

Since AngularJS is now a deprecated framework, you can use JavaScript modern frameworks like Vuejs, React and Angular, instead.

AngularJs wouldn't be so powerful, If it hadn't It's components to solve problems like these. AngularJs suggests us Services and Factories (sometimes Values and Constants) to have global actions and variables for controllers and for many other AngularJs components.Lets see how we can define a simple Service

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
          });
       }
       ....
    }
  }])

The same thing you can make, using AngularJs Factory.Just the same way, only replace "service" with "factory".Now lets see what how we can use that service.Lets define a simple controller and use that service.

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)
          .success(function(res, ...){
            // on success function
          })
          .error(function(res, ...){
            // on error function
          })
      }

      ...
    }
  }])

As you see, Service and Factories let us to have some service functions, to communicate to the server, store data, etc...

AngularJs lets us to use Services and Factories inside other AngularJs components like Directives, Factories, Even inside Services.


Do you find this helpful?

Related articles