Angular 15 Services complete tutorial with examples

This tutorial talks about complete details about Angular services with examples.

In Angular Application, Components get the data from API which hit MySQL database and displays on browser API. So we have to write a code to consume API code in the component. Suppose multiple components use the same API, which means we have to write the same API to consume code in all components.

Suppose, If any change in API consumes logic, We have to change in multiple places.

To solve this, Angular introduced services using dependency injection.

What is Angular Service?

Service in Angular is a normal class with properties and reusable functions. These functions are called angular components, directives, and other services.

Advantages of Angular Services

  • It acts as a delegation layer between the component view and model
  • Separating data access logic and promoting code modularity and reusable
  • Easily share data between multiple components

How to Create Angular Service?

In the Angular application, You can create using the below ng CLI commands

ng generate service servicename
or
ng g s servicename

Here is an output of the above command


B:\blog\angular-app-testing>ng g s employee
CREATE src/app/employee.service.spec.ts (367 bytes)
CREATE src/app/employee.service.ts (137 bytes)

Given employee as a service name and it creates two files

  • Service class:employee.service.ts
  • Service spec class: employee.service.spec.ts

Here is an employee.service.ts class created

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

@Injectable({
  providedIn: "root",
})
export class EmployeeService {
  constructor() {}
}

@Injectable is an Angular decorator that can be used as a dependency in other components.

providedIn is a metadata attribute where this service is going to be used, which means this can be used in components or modules. providedIn: ‘root’ makes this service available at the application root. This will be the default value when you created with the ng generate service command

It creates a singleton and shared class during runtime.

The service uses Global and Local component scopes.

Angular Service scopes

Services in Angular can be declared in global(Application module) or component.

Global Module Service

In this, the Service class is declared in the application module- app.module.ts

How service is created on global scope?

  • The service instance is created the first time when the first component or directive user instance is created and loaded
  • The single service is shared among all instances of a component in a module
  • Service class is destroyed once the application module is destroyed or the page is unloaded.

The following are steps to configure global service.

  • import Service in application module file - app.module.t

    s

  • Update the Service class in the providers section of NgModule

This registers as a global service and is available in all components of the @ngModule.

import { NgModule } from "@angular/core";

import { EmployeeService } from "./employee.service";

@NgModule({
  declarations: [],
  imports: [],
  providers: [EmployeeService],
  bootstrap: [AppComponent],
})
export class AppModule {}

Local Service in Angular

Local service configures in Components, Directive, and pipes.

Here is the life cycle of local service

  • New Service instance is created once the angular component(directive, pipes) instance is created and loaded
  • Every time a new service instance is created whenever a component instance is created
  • Service is destroyed whenever the component unloads or is destroyed.

In this example, Service is injected into the component itself, which means a service instance is created during component creation.

The single-component has a single copy of the service instance.

  • Import Service class into component
  • Configure Service in provider attribute of @component metadata
import { Component } from "@angular/core";
import { EmployeeService } from "./employee.service";
import { StaticClass } from "./StaticClass";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"],
  providers: [EmployeeService],
})
export class AppComponent {
  title = "";

  constructor() {}
}

Angular Service methods

It contains methods for reusable code across all components.

In real-time applications, Angular services are used for API operations like Create, Read, Update, and Delete operations.

Let’s see CRUD operations for consuming API Angular provides a HttpClient service to consume external APIs.

To use HttpClient, We have to first import HttpClientModule in the Angular application module

import { NgModule } from "@angular/core";

import { HttpClientModule } from "@angular/common/http";

@NgModule({
  declarations: [],
  imports: [HttpClientModule],
  providers: [],
  bootstrap: [],
})
export class AppModule {}

Now you can use the HttpClient service in your service.

Inject HttpClient in the constructor of your service as seen below

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

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  constructor(private httpClient: HttpClient) { }
}

Let’s add methods to the Angular service

API url is declared as a private variable and added methods

Here is an Angular Service example

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from "rxjs/operators";
import { catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {
  private employee_api_url: string = 'api.localhost.com';

  constructor(private httpClient: HttpClient) { }

  createEmployee(employee: any): Observable<any> {
    return this.httpClient.post(this.employee_api_url + '/create', employee)
      .pipe(map((resp: any) => resp.json()),
        catchError(error => this.throwError(error))
      )

  }
  getEmployees(): Observable<any> {
    return this.httpClient.get(this.employee_api_url + '/read')
      .pipe(map((resp: any) => resp.json()),
        catchError(error => this.throwError(error))
      )

  }
  updateEmployee(employee: any): Observable<any> {
    return this.httpClient.get(this.employee_api_url + '/update')
      .pipe(map((resp: any) => resp.json()),
        catchError(error => this.throwError(error))
      )

  }
  deleteEmployee(id: number): Observable<any> {
    return this.httpClient.delete(this.employee_api_url + '/delete/{id}')
      .pipe(map((resp: any) => resp.json()),
        catchError(error => this.throwError(error))
      )

  }
  throwError(error: any) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
  }

}

Using Service in Angular components

Let’s see how we can access Angular Service in a component

  • Import Service into Angular component
  • Configure EmployeeService in providers of @Component metadata
  • Inject EmployeeService in the constructor of a component

Here is an example

import { Component } from '@angular/core';
import { EmployeeService } from './employee.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers: [EmployeeService]
})
export class AppComponent {
  title = '';
  emps: [] = [];
  constructor(private employeeService: EmployeeService) { }

  ngOnInit() {
    this.employeeService.getEmployees().subscribe((data) => {
      this.emps = data;
    }, (error) => {
      console.log("An error accessing Employee Service");
    })
  }
}

What is the difference between Service and a component

Components and services are the basic building blocks of an angular framework.

Let’s see some differences between them

ComponentsService
Components are UI to display on browserServices contain common functions for data processing logic
Can be created with @component decoratorcreated with @Injectable decorator
Components can be independent or can use another componentServices are used across all components, can use other services
It contains reusable UI HTML functionalityIt contains data accessing logic to be reusable by components
It contains HTML, CSS, and data binding logicContains data process and access logic
component is not a singleton, can have multiple instancesSingleton instance across entire application

Conclusion

In this post, you learned a complete tutorial about Angular service with examples for

  • what is Angular service
  • How to create an angular service
  • How to access services in Angular components
  • Angular global and local scope
  • Difference between service and component
  • Advantages of Angular services