Dependency Injection in Services

Loading

1. What is Dependency Injection (DI)?

Dependency Injection (DI) is a design pattern used in AngularJS to manage dependencies efficiently. It allows injecting services, factories, or values into other components like controllers, directives, and other services.

Why Use Dependency Injection?

Improves Code Reusability – Services can be injected into multiple components.
Enhances Maintainability – Dependencies are managed centrally, making modifications easier.
Encourages Loose Coupling – Components don’t need to create dependencies manually.
Facilitates Unit Testing – Mock dependencies can be injected for testing.


2. Using Dependency Injection in Services

AngularJS automatically injects required dependencies into services when they are declared.

Example: Injecting $http into a Service

The $http service is used for making API calls.

var app = angular.module("myApp", []);

app.service("UserService", function($http) {
this.getUsers = function() {
return $http.get("https://jsonplaceholder.typicode.com/users");
};
});

How to Use the Service in a Controller

app.controller("UserController", function($scope, UserService) {
UserService.getUsers().then(function(response) {
$scope.users = response.data;
});
});

UserService depends on $http, which AngularJS injects automatically.


3. Injecting Multiple Dependencies into a Service

You can inject multiple services inside another service.

Example: Injecting $http and $q

$q helps in handling promises and asynchronous operations.

app.service("ProductService", function($http, $q) {
this.getProducts = function() {
var deferred = $q.defer();
$http.get("https://fakestoreapi.com/products")
.then(function(response) {
deferred.resolve(response.data);
})
.catch(function(error) {
deferred.reject(error);
});
return deferred.promise;
};
});

How to Use It in a Controller

app.controller("ProductController", function($scope, ProductService) {
ProductService.getProducts().then(
function(products) {
$scope.products = products;
},
function(error) {
console.error("Error fetching products", error);
}
);
});

This service fetches product data and handles API errors using $q.


4. Injecting One Service into Another

A service can depend on another service to enhance modularity.

Example: Logging Service Used in Another Service

app.service("LoggerService", function() {
this.log = function(message) {
console.log("LOG:", message);
};
});

app.service("OrderService", function($http, LoggerService) {
this.getOrders = function() {
LoggerService.log("Fetching orders...");
return $http.get("https://fakestoreapi.com/orders");
};
});

How to Use the Service

app.controller("OrderController", function($scope, OrderService) {
OrderService.getOrders().then(function(response) {
$scope.orders = response.data;
});
});

🔹 LoggerService is injected into OrderService to handle logging.


5. Injecting Constants and Values into Services

AngularJS allows injecting predefined values or constants.

Using .constant()

Constants are global values that cannot be changed once set.

app.constant("API_URL", "https://fakestoreapi.com");
app.service("ConfigService", function(API_URL) {
this.getApiUrl = function() {
return API_URL;
};
});

Using .value()

Values can be changed during runtime.

app.value("userRole", "admin");
app.service("RoleService", function(userRole) {
this.getUserRole = function() {
return userRole;
};
});

6. Using $inject for Explicit Dependency Injection

AngularJS uses implicit injection by default, but you can define dependencies explicitly using $inject.

Example: Using $inject

app.service("CartService", ['$http', function($http) {
this.getCartItems = function() {
return $http.get("https://fakestoreapi.com/cart");
};
}]);

OR

app.service("CartService", function($http) {
this.getCartItems = function() {
return $http.get("https://fakestoreapi.com/cart");
};
});
CartService.$inject = ['$http'];

Explicit injection prevents minification issues in production.

Leave a Reply

Your email address will not be published. Required fields are marked *