Services and Dependency Injection

Go back to Tutorial

For data or logic that is not associated with a specific view, and that you want to share across components, you create a service class. A service class definition is immediately preceded by the @Injectable decorator. The decorator provides the metadata that allows your service to be injected into client components as a dependency.

Dependency injection (or DI) lets you keep your component classes lean and efficient. They don’t fetch data from the server, validate user input, or log directly to the console; they delegate such tasks to services.


Service is a broad category encompassing any value, function, or feature that an app needs. A service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well.

Angular distinguishes components from services to increase modularity and reusability. By separating a component’s view-related functionality from other kinds of processing, you can make your component classes lean and efficient.

Ideally, a component’s job is to enable the user experience and nothing more. A component should present properties and methods for data binding, in order to mediate between the view (rendered by the template) and the application logic (which often includes some notion of a model).

A component can delegate certain tasks to services, such as fetching data from the server, validating user input, or logging directly to the console. By defining such processing tasks in an injectable service class, you make those tasks available to any component. You can also make your app more adaptable by injecting different providers of the same kind of service, as appropriate in different circumstances.

Angular doesn’t enforce these principles. Angular does help you follow these principles by making it easy to factor your application logic into services and make those services available to components through dependency injection.

Service examples

Here’s an example of a service class that logs to the browser console.

src/app/logger.service.ts (class)

export class Logger {

log(msg: any)   { console.log(msg); }

error(msg: any) { console.error(msg); }

warn(msg: any)  { console.warn(msg); }


Services can depend on other services. For example, here’s a HeroService that depends on the Logger service, and also uses BackendService to get heroes. That service in turn might depend on the HttpClient service to fetch heroes asynchronously from a server.

src/app/hero.service.ts (class)

export class HeroService {

private heroes: Hero[] = [];


private backend: BackendService,

private logger: Logger) { }

getHeroes() {

this.backend.getAll(Hero).then( (heroes: Hero[]) => {

this.logger.log(`Fetched ${heroes.length} heroes.`);

this.heroes.push(…heroes); // fill cache


return this.heroes;



For many services, like the $location service, it seems like you could use objects that are already in the DOM, like the window.location object, and you could, but it would have some limitations, at least for your AngularJS application.

AngularJS constantly supervises your application, and for it to handle changes and events properly, AngularJS prefers that you use the $location service instead of the window.location object.

The $http Service – The $http service is one of the most common used services in AngularJS applications. The service makes a request to the server, and lets your application handle the response.

Example  – Make a simple request to the server, and display the result in a header:

<div ng-app=”myApp” ng-controller=”myCtrl”>

<p>Today’s welcome message is:</p>




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

app.controller(‘myCtrl’, function($scope, $http) {


.then(function(response) {

$scope.myWelcome =;




Methods – The example above uses the .get method of the $http service. The .get method is a shortcut method of the $http service. There are several shortcut methods: .delete(), .get(), .head(), .jsonp(), .patch(), .post(), .put()

Properties – The response from the server is an object with these properties:

  • .config the object used to generate the request.
  • .data a string, or an object, carrying the response from the server.
  • .headers a function to use to get header information.
  • .status a number defining the HTTP status.
  • .statusText a string defining the HTTP status.

Create Your Own Service – To create your own service, connect your service to the module:

Create a service named hexafy:

app.service(‘hexafy’, function() {

this.myFunc = function (x) {

return x.toString(16);



To use your custom made service, add it as a dependency when defining the controller:

Example – Use custom service named hexafy to convert a number into a hexadecimal number:

app.controller(‘myCtrl’, function($scope, hexafy) {

$scope.hex = hexafy.myFunc(255);


Go back to Tutorial

Get industry recognized certification – Contact us