Create Services In Angular Application

Introduction

 
In this article, we are going to explore the steps needed to create services in Angular applications along with the concept of dependency injection.
 

What is dependecy Injection and why do we use it ?

 
Dependency Injection (DI) is a mechanism where the required resources will be injected into the code automatically. Angular comes with a in-built dependency injection subsystem. 
  • DI allows developers to reuse the code across application. 
  • DI makes the application development and testing much easier.
  • DI makes the code loosely coupled.
  • DI allows the developer to ask for the dependencies from Angular. There is no need for the developer to explicitly create/instantiate them.

What is Service and why do we use it?

  • A service in Angular is a class which contains some functionality that can be reused across the application. A service is a singleton object. Angular services are a mechanism of abstracting shared code and functionality throughout the application.
  • Angular Services come as objects which are wired together using dependency injection.
  • Angular provides a few inbuilt services. We can also create custom services.

Why Services?

  • Services can be used to share the code across components of an application.
  • Services can be used to make HTTP requests.

Creating a Service

 
Create a service class using the following command.
  1. ng generate service Article     
The above command will create a service class (article.service.ts) as shown below. 
  1. import { Injectable } from '@angular/core';    
  2.     
  3. @Injectable({    
  4.   providedIn: 'root'    
  5. })    
  6. export class ArticleService {    
  7.     
  8.   constructor() { }    
  9. }   
@Injectable() decorator makes the class injectable into application components.
 

Providing a Service

 
Services can be provided in an Angular applications in any of the following ways:
 
The first way  to register service is to specify providedIn property using @Injectable decorator. This property is added by default when you generate a service using Angular CLI. 
  1. import { Injectable } from '@angular/core';    
  2.     
  3. @Injectable({    
  4.   providedIn: 'root'    
  5. })    
  6. export class ArticleService {    
  7.     
  8.   constructor() { }    
  9. }    
Line 4: providedIn property registers articleService at the root level (app module).
 
When the ArticleService is provided at the root level, Angular creates a singleton instance of the service class and injects the same instance into any class that uses this service class. In addition, Angular also optimizes the application if registered through providedIn property by removing the service class if none of the components use it. 
 
There is also a way to limit the scope of the service class by registering it in the providers' property inside @Component decorator. Providers in component decorator and module decorator are independent. Providing a service class inside component creates a separate instance for that component and its nested components. 
 
Add the below code in app.components.ts,
  1. import { Component } from '@angular/core';    
  2. import { ArticleService } from './article.service';    
  3. @Component({    
  4.   selector: 'app-root',    
  5.   templateUrl: './app.component.html',    
  6.   styleUrls: ['./app.component.css'],    
  7.   providers : [ArticleService]    
  8. })    
  9. export class AppComponent {    
  10.   title = 'FormsProject';    
  11. }  
Services can also be provided across the application by registering it using providers property in @Ngmodule decorator of any module.
  1. import { BrowserModule } from '@angular/platform-browser';    
  2. import { NgModule } from '@angular/core';    
  3. import { ReactiveFormsModule } from '@angular/forms';    
  4. import { AppRoutingModule } from './app-routing.module';    
  5. import { AppComponent } from './app.component';    
  6. import {Form, FormsModule} from '@angular/forms';    
  7. import { ArticleFormComponent } from './article-form/article-form.component';    
  8. import { RegistrationFormComponent } from './registration-form/registration-form.component';    
  9. import { ArticleService } from './article.service';    
  10. @NgModule({    
  11.   declarations: [    
  12.     AppComponent,    
  13.     ArticleFormComponent,    
  14.     RegistrationFormComponent    
  15.   ],    
  16.   imports: [    
  17.     BrowserModule,    
  18.     AppRoutingModule,    
  19.     FormsModule,    
  20.     ReactiveFormsModule    
  21.   ],    
  22.   providers: [ArticleService],    
  23.   bootstrap: [AppComponent]    
  24. })    
  25. export class AppModule { }   
Line 22: When the service class is added in the providers property of the root module, all the directives and components will have access to the same instance of the service. 
 

Injecting a Service

 
The only way to inject a service into a component/directive or any other class is through a constructor. Add a constructor in a component class with service class as an argument as shown below,
 
Here, ArticleService will be injected into the component through constructor injection by the framework. 
  1. import { Component } from '@angular/core';    
  2. import { ArticleService } from './article.service';    
  3. @Component({    
  4.   selector: 'app-root',    
  5.   templateUrl: './app.component.html',    
  6.   styleUrls: ['./app.component.css'],    
  7.   providers : [ArticleService]    
  8. })    
  9. export class AppComponent {    
  10.   title = 'FormsProject';    
  11.     
  12.   constructor(private articleService: ArticleService){ }    
  13. }    
Problem Statement
 
Create an Article Component which fetches article details like id, name and displays them on the page in a list format. Store the article details in an array and fetch the data using a custom service.
 

Demosteps

 
Create ArticleComponent by using the following CLI command
  1. ng generate component Article    
Create a file with name Article.ts under book folder and add the following code. 
  1. export class Article {    
  2.     id: number;    
  3.     name: string;    
  4. }  
Create a file with name Article-data.ts under book folder and add the following code. 
  1. import {Article} from './Article';    
  2. export var ARTICLES: Article[] = [    
  3.     { "id": 1, "name""Angular Basic" },    
  4.     { "id": 2, "name""Template in Angular" },    
  5.     { "id": 3, "name""Nested component" },    
  6.     { "id": 4, "name""Reactive component" },    
  7.     { "id": 5, "name""Change detection technique" }    
  8. ];   
Create a service called ArticleService under book folder using the following CLI command,
  1. ng generate service Article    
Add the following code in article.service.ts 
  1. import { Injectable } from '@angular/core';    
  2. import {ARTICLES} from './Article-data';    
  3. import {Article} from './Article';    
  4.     
  5. @Injectable({    
  6.   providedIn: 'root'    
  7. })    
  8. export class ArticleService {    
  9.     
  10. getArticles ()     
  11. {    
  12.   return ARTICLES;    
  13. }    
  14. }   
Add the following code in article.component.ts file 
  1. import { Component, OnInit } from '@angular/core';    
  2. import {ArticleService} from './article.service';    
  3. import { Article } from './Article';    
  4. @Component({    
  5.   selector: 'app-article',    
  6.   templateUrl: './article.component.html',    
  7.   styleUrls: ['./article.component.css']    
  8. })    
  9. export class ArticleComponent implements OnInit {    
  10. articles : Article[];    
  11.     
  12.   constructor(private articelService : ArticleService) { }    
  13.   getArticles()    
  14.   {    
  15.     this.articles=this.articelService.getArticles()    
  16.   }    
  17.   ngOnInit() {     
  18.     this.getArticles()    
  19.   }    
  20. }   
Write the below-given code in article.component.html 
  1. <h2>My Articles</h2>    
  2. <ul class="Articles">    
  3.   <li *ngFor="let article of Articles">    
  4.     <span class="badge">{{article.id}}</span> {{article.name}}    
  5.   </li>    
  6. </ul>  
Add the following code in article.component.css which has styles for books.
  1. .Articles {    
  2.     margin: 0 0 2em 0;    
  3.     list-style-type: none;    
  4.     padding: 0;    
  5.     width: 15em;    
  6. }    
  7. .Articles li {    
  8.     cursor: pointer;    
  9.     position: relative;    
  10.     left: 0;    
  11.     background-color: #EEE;    
  12.     margin: .5em;    
  13.     padding: .3em 0;    
  14.     height: 1.6em;    
  15.     border-radius: 4px;    
  16. }    
  17. .Articles li:hover {    
  18.     color: #607D8B;    
  19.     background-color: #DDD;    
  20.     left: .1em;    
  21. }    
  22. .Articles .badge {    
  23.     display: inline-block;    
  24.     font-size: small;    
  25.     color: white;    
  26.     padding: 0.8em 0.7em 0 0.7em;    
  27.     background-color: #607D8B;    
  28.     line-height: 1em;    
  29.     position: relative;    
  30.     left: -1px;    
  31.     top: -4px;    
  32.     height: 1.8em;    
  33.     margin-right: .8em;    
  34.     border-radius: 4px 0 0 4px;    
  35. }   
Add the following code in app.component.html.
  1. <app-article></app-article>    
Save the files and check the output in the browser,

Summary

 
In this article, we explored the steps needed to create the services in Angular applications along with the concept of dependency injection. Hope you like the article. Until next time - Happy Reading Cheers