---
title: "Explain AngularJS services with examples."  
description: "Explain AngularJS services with examples."  
author: "Sandra Emily"  
published: 2024-06-24  
updated: 2024-06-25  
canonical: https://www.mindstick.com/forum/160773/explain-angularjs-services-with-examples  
category: "angular js"  
tags: ["web development", "angular js", "front-end development"]  
reading_time: 3 minutes  

---

# Explain AngularJS services with examples.

[Explain](https://www.mindstick.com/forum/157854/what-is-system-debugging-explain-some-system-debugging-tools-used-in-modern-computer-systems) AngularJS services with examples.

## Replies

### Reply by Ravi Vishwakarma

[**AngularJS services**](https://www.mindstick.com/articles/335832/services-and-dependency-injection-in-angularjs) are singleton objects or functions that are used to organize and share code across an application. They are a core component of AngularJS and facilitate the separation of concerns by providing a way to encapsulate reusable code, making it available to different parts of the application. Services are typically used for data fetching, business logic, and utility functions.

#### Creating and Using Services

[**Built-in Services**](https://www.mindstick.com/articles/335832/services-and-dependency-injection-in-angularjs)

AngularJS provides several built-in services, such as `$http` for making HTTP requests, `$timeout` for delaying execution, and `$interval` for periodic execution. These services can be injected into controllers, directives, filters, and others.

```javascript
// Service to handle HTTP requests
app.service('UserService', ['$http', '$log', function ($http, $log) {
    var baseUrl = 'https://jsonplaceholder.typicode.com/users';
    this.getUsers = function () {
        $log.log(baseUrl);
        return $http.get(baseUrl);
    };
}]);

// here '$scope', 'UserService' is dependency injection on controller
app.controller('myController', ['$scope', 'UserService', function ($scope, UserService) {
    // Function to fetch data
    $scope.getUserData = function () {
        UserService.getUsers()
        .then(function (response) {
            $scope.users = response.data; // return the response data
        }, function (error) {
            console.error('Error fetching data:', error);
        });
    };
    // Call the function to fetch data on controller load
    $scope.getUserData();
}]);
```

[**Custom Services**](https://www.mindstick.com/blog/304402/create-custom-services-in-angularjs)

You can create custom services using the `service`, `factory`, or `provider` methods. Here’s an overview of each approach with examples:

**1. Using the** `service` **Method**

The `service` method creates a service by instantiating a constructor function.

```javascript
// Define the module
var app = angular.module('myApp', []);

// Define a service
app.service('MathService', function() {
    this.add = function(a, b) {
        return a + b;
    };
    this.subtract = function(a, b) {
        return a - b;
    };
});

// Inject and use the service in a controller
app.controller('MainController', ['$scope', 'MathService', function($scope, MathService) {
    $scope.addition = MathService.add(5, 3);  // 8
    $scope.subtraction = MathService.subtract(5, 3);  // 2
}]);
```

**2. Using the** `factory` **Method**

The `factory` method allows for more flexible service creation by returning an object or a function.

```javascript
// Define the module
var app = angular.module('myApp', []);

// Define a factory
app.factory('MathFactory', function() {
    var factory = {};

    factory.multiply = function(a, b) {
        return a * b;
    };

    factory.divide = function(a, b) {
        if (b === 0) return 'Error';
        return a / b;
    };

    return factory;
});

// Inject and use the factory in a controller
app.controller('MainController', ['$scope', 'MathFactory', function($scope, MathFactory) {
    $scope.multiplication = MathFactory.multiply(5, 3);  // 15
    $scope.division = MathFactory.divide(5, 0);  // Error
}]);
```

**3. Using the** `provider` **Method**

The `provider` method provides the most flexibility, allowing for configuration during the application’s configuration phase.

```javascript
// Define the module
var app = angular.module('myApp', []);

// Define a provider
app.provider('MathProvider', function() {
    var precision = 1;

    this.setPrecision = function(p) {
        precision = p;
    };

    this.$get = function() {
        return {
            round: function(value) {
                return value.toFixed(precision);
            }
        };
    };
});

// Configure the provider
app.config(['MathProviderProvider', function(MathProviderProvider) {
    MathProviderProvider.setPrecision(2);
}]);

// Inject and use the provider in a controller
app.controller('MainController', ['$scope', 'MathProvider', function($scope, MathProvider) {
    $scope.roundedValue = MathProvider.round(5.678);  // 5.68
}]);
```

## Key Points

- **Service**: A singleton object instantiated by a constructor function.
- **Factory**: A more flexible approach where an object or function is returned.
- **Provider**: The most configurable approach, useful for complex service configuration and setup.

## Read more

[**Factory vs Service in AngularJS, Which one better?**](https://www.mindstick.com/blog/304231/factory-vs-service-in-angularjs-which-one-better)

[**Create Custom Services in AngularJS**](https://www.mindstick.com/blog/304402/create-custom-services-in-angularjs)

[**Describe the life-cycle of AngularJs Service and Controller**](https://www.mindstick.com/articles/335777/describe-the-life-cycle-of-angularjs-service-and-controller)

[**Services and Dependency Injection in AngularJS**](https://www.mindstick.com/articles/335832/services-and-dependency-injection-in-angularjs)


---

Original Source: https://www.mindstick.com/forum/160773/explain-angularjs-services-with-examples

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
