AngularJs 2 Series: Concept of Services


AngularJs 2 Series: Concept of Services In this article I will demonstrate the concept of Services in AngularJs 2. I will show you how to develop a custom alert service that displays a message as an alert notification. We will use Angular CLI (Command Line Interface) to build the AngularJs 2 Service. The article assumes that you have already setup AngularJs with CLI. For more information on setting up Angular CLI you can refer to Build Your Own Component article.

Services are common business functions that are used across Angular application. One good example would be a logging service.
Example of Logging Service Design
Assuming your Angular application has some of the components performing the logging for audit purpose. In such a case, you will end up have a log method in each of these components. This obviously is a bad design approach as the log method is duplicated across components. If you want to change the semantics of logging then you will need to change the code in all these components which in turn will impact the whole application. So a good design approach will be to have a common service component performing the logging feature. The log method in each of the components will be removed and placed in the specific logging service class. The components can use the logging feature by injecting the logging service. Service injection is one form of dependency injection provided by Angular.

Design Considerations

Services can be used to interact with data. It can be used to provide connection to database and define functions that operate on data like CRUD operations. One can also design the service to provide a remote access to a web resource. It can be used to provide common integration needs like invoking a API of another application. Services can also be an excellent choice to design communication between components of your Angular application. You can build a service that provides a common event handling platform. Last but not the least, one can centralize common business functions used across the application as services. There are various approaches one can take to design a service. While designing services, think common functionality that every aspect of your application uses and transform them into services.

Creating Alert Service

We will create a service named AlertService that will display message as an alert notification. We will use Angular CLI tool to create our service. Open the Node.js command prompt, navigate to <your-project-home>\src\app folder and run the following command:

ng generate service alert

The above command will create two files viz. alert.service.spec.ts and alert.service.ts. You can safely ignore the ‘.spec.ts’ file as this is for testing purpose. Lets look at the alert.service.ts file:

import { Injectable } from '@angular/core';

export class AlertService {

	alert(message: string) {

	constructor() { }


The class is automatically named as AlertService. Lets understand the structure of the class. You will observe the @Injectable decorator automatically defined in the class. It means this alert service and any of its dependencies can be automatically injected by other component. As our alert service does not have any dependency with any other service, we can safely omit the @Injectable decorator. Though for design readability Angular recommends that you always define the @Injectable decorator whenever you create any service. We have added the alert() method which simply uses JavaScript native alert function to display the message.
One more important thing to do is to make our AlertService service available to the whole application through the use of providers meta data. The providers meta data must be defined in the app.module.ts (main application module file) file. If you provide the service in a main module file then it is visible to whole application. If you provide it in any component then only that component can use the service. By providing the service at the module level, Angular creates only one instance of AlertService class which can be used by all the components in an application.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { AlertService } from './alert.service';
import { OrderSuccessNotificationComponent } from './order-success-notification.component';

  declarations: [
  imports: [
  providers: [AlertService],
  bootstrap: [AppComponent]
export class AppModule { }

The above app.module.ts file has the providers meta data which has our AlertService class defined. Now we can inject this alert service in any component. If you do not provide your service, it cannot be injected by Angular at runtime.

Just like most of the other server and client side frameworks, Angular 2 also has the concept of Dependency Injection. Instances of services or classes can be injected using the constructor. Angular provides the concept of providers meta data to provide a service or any class as a candidate for automatic injection, at runtime, by defining that service or a class in a constructor of the dependent class.

We will create a order success component named OrderSuccessNotificationComponent that will inject our AlertService service class through the constructor to notify the user about the order being processed successfully. For more information on creating Angular components refer to Build Your Own Component article.

import { Component } from '@angular/core';
import { AlertService } from './alert.service';

  selector: 'order-success',
  template: `
  styles: []
export class OrderSuccessNotificationComponent {

	private status: string = "Order created successfully";
	constructor(private alertService: AlertService) {


Note the use of order-success selector that can be used to display the notification encapsulated in the status variable. Place this element <order-success> in the bootstrap (starting) component of your application. Upon running the application you will see the order success alert notification. The example provided might look trivial but the larger objective is to show how you can make use of services to define common business functionality and use in your application.

Leave a Reply

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