What is Angular Services - Types of services in Angular with Examples

What is Angular Services - Types of services in Angular with Examples

21 Aug 2024
Intermediate
4.4K Views
19 min read
Learn with an interactive course and practical hands-on labs

Self-Paced Angular Certification Course

Services in Angular: An Overview

Services in Angular are meant for specifically making the call to RestFul API, getting the data, and passing data to all components whichever component subscribes to it. Moreover, it gives us the benefit of code reusability and data sharing across components.

Read More: What is Angular?

Goals

  1. How to create a basic service in Angular
  2. How to subscribe to the service response.
  3. How to handle errors in service.

Specifications

In this Angular tutorial, we will create a basic Angular application and try to use the service to get data and pass the data component. Exploring an Angular Course can offer a deeper dive into utilizing services within Angular applications.

Why Services

What in Angular are Services?

The component is meant to provide the data to view. When I say view, it means providing the data to respective HTML whatever is required. It is not a good practice to make an API call directly from the component. Services give the benefit of separation of concerns and you can say the single responsibility principle as well.

Read More: Top 50+ Angular Interview Questions & Answers

Let's see Services in Action

  1. Create an angular project: go to VS Code integrated terminal
    
    Run - ng new ServiesTest
    
  2. Run this newly created project by using the below command
    
    ng serve
    

    Once you run this command you must see the below page at http://localhost:4200/

    welcome to angular
  3. Create a service by using the below command
    
    ng g s DateTime
    
  4. Now go to the DateTimeService.ts file you will find below the code
    
    import { Injectable } from '@angular/core';
    
    @Injectable({
     providedIn: 'root'
    })
    export class DateTimeService {
    
     constructor() { }
    }
    

    If you notice it has the @Injectable decorator similar to the @Component decorator which we used to have in an angular component. @Injectable means it can participate in dependency injection.@Injectable accepts metadata objects. So here you can have providedIn value as root, which means this service can be injected into any of the classes across the project.

  5. Now let us write the code to consume the actual service. So here I am trying to call a real-time RestFul API which is fromhttps://www.jsontest.com/
  6. We will call an API located at : http://date.jsontest.com So here is the code for the same:
    
    import { Injectable } from '@angular/core';
    
    @Injectable({
     providedIn: 'root'
    })
    export class DateTimeService {
    
     public apiURL:string="http://date.jsontest.com";
     constructor() { }
    
     getDateTime ()
     {
     return this.httpClient.get(this.apiURL)
     .pipe(
     map(res => res),
     catchError( this.errorHandler)
     );
     }
    
    }
    

    So my code is complaining about httpClient, map, catchError, and errorHandler.

  7. So let us do the import for these complaints.

    
    import { HttpClient } from '@angular/common/http'; 

    For httpClient inject in the constructor like below:

    
    constructor(private httpClient:HttpClient) { }
    import { map, catchError } from 'rxjs/operators';
    For map, catchError 
    Now it's time to fix errorHandler.
    So write one method like below:
    
    errorHandler(error: Response) { 
     console.log(error); 
     return throwError(error); 
    }
    

    Lastly, do this import :

    
    import {throwError} from 'rxjs'
    

    So finally service code looks like this:

    
    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import {throwError} from 'rxjs'
    import { map, catchError } from 'rxjs/operators';
    
    @Injectable({
     providedIn: 'root'
    })
    export class DateTimeService {
    
     public apiURL:string="http://date.jsontest.com";
     constructor(private httpClient:HttpClient) { }
    
     getDateTime ()
     {
     return this.httpClient.get(this.apiURL)
     .pipe(
     map(res => res),
     catchError( this.errorHandler)
     );
     }
     errorHandler(error: Response) { 
     console.log(error); 
     return throwError(error); 
    } 
    }
    

    If any error while calling the service it will be logged in the console and an error will be thrown to the subscriber. Now is the time to consume this service from the component. So here you go.

    Go to app.module.ts and import
    
    import { HttpClient,HttpClientModule } from '@angular/common/http';
    

    Use this import in an import array like this

    
    imports: [
     BrowserModule,HttpClientModule
     ],
    

    First of all, you need to inject this service into components like this:

    
    constructor(private dateTimeService:DateTimeService){}
    

    So here now by using this dateTimeService injector, we will call the service method like this

    
    ngOnInit()
     {
     this.dateTimeService.getDateTime()
     .subscribe((result) => {
     this.globalResponse = result; 
     },
     error => { //This is error part
     console.log(error.message);
     },
     () => {
     // This is Success part
     console.log("Date time fetched sucssesfully.");
     console.log(this.globalResponse);
     }
     )
    
     }
    

    Here we are calling the getDateTime method from the service, which will call http://date.jsontest.com and return us the output in the below format.

    
    {
     "time": "03:53:25 AM",
     "milliseconds_since_epoch": 1362196405309,
     "date": "03-02-2013"
    }
    

    We are subscribing to the service response here in the component. Similarly, in this way, you can consume this service in any of your components because the service is injected in the root. So in my component, as you can see I am storing the service response in the global response. Since we have logged the service response in the console, you can see the response in the console something like this.

    Let us bind this variable to HTML. Go to app.component.html and paste this code :

     
    <div style="text-align:center">
     <h1>
     Welcome to {{ title }}!
     </h1>
     <h2>Current date {{globalResponse.date}}</h2>
     <h2>Current Time {{globalResponse.time}}</h2>
     </div>
    

    Run the project, your output will be like this

    Now let me give all required files source code:

    App.module.ts

    
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { HttpClient,HttpClientModule } from '@angular/common/http';
    
    import { AppComponent } from './app.component';
    
    @NgModule({
     declarations: [
     AppComponent
     ],
     imports: [
     BrowserModule,HttpClientModule
     ],
     providers: [],
     bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    date-time.service.ts

    
    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import {throwError} from 'rxjs'
    import { map, catchError } from 'rxjs/operators';
    
    @Injectable({
     providedIn: 'root'
    })
    export class DateTimeService {
    
     public apiURL:string="http://date.jsontest.com";
     constructor(private httpClient:HttpClient) { }
    
     getDateTime ()
     {
     return this.httpClient.get(this.apiURL)
     .pipe(
     map(res =>res),
     catchError( this.errorHandler)
     );
     }
     errorHandler(error: Response) { 
     console.log(error); 
     return throwError(error); 
    }
    }
    

    app.component.ts

    
    import { Component,OnInit } from '@angular/core';
    import { DateTimeService } from './date-time.service';
    
    @Component({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
     title = 'DotNet Techy YouTube Channel Services in Angular 6 Demo';
     public globalResponse: any;
     constructor(private dateTimeService:DateTimeService){}
    
     ngOnInit()
     {
     this.dateTimeService.getDateTime()
     .subscribe((result) => {
     this.globalResponse = result; 
     },
     error => { //This is error part
     console.log(error.message);
     },
     () => {
     // This is Success part
     console.log("Date time fetched sucssesfully.");
     console.log(this.globalResponse);
     console.log("Thanks to DotNet Techy Youtube channel who taught me, how to create services in Angular 6.");
     }
     )
    
     }
     }
    

    app.component.html

    
    <div style="text-align:center">
     <h1>
     Welcome to {{ title }}!
     </h1>
     <h2>Current date {{globalResponse.date}}</h2>
     <h2>Current Time {{globalResponse.time}}</h2>
    </div>

Read More:

Summary

Services are the backbone of every Angular application and the services in Angular come into the picture to resolve the issues as instead of repeating the same business logic, it centralizes our business logic in one place. It is very handy while working with Angular applications because it can be easily injected via dependency injection. In-depth exploration of services and their implementation is a crucial aspect covered in Angular Training.

They are also very useful if you want to use the same instance of one class everywhere in your class. services are nothing but just classes as discussed in this article. Other than components, services may only contain logic. and one thing to be kept in mind is that it should be completely separated from the angular template.

Take our Angular skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article
About Author
Deep Gautam (Technical Manager, Full Stack Developer)

He is a Technical Manager, Full Stack Developer, Author and YouTuber(DotNet Techy). He has more than 10 years of industry expertise on Angular, .NET, ASP.NET, WEB API, MVC and .NET Core. He is passionate about learning and sharing new technical stacks.
Accept cookies & close this