{

Angular 12 Services complete tutorial with examples


This tutorial talks about complete details about Angular services with examples. Angular 12 service tutorial and 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 component. Suppose multiple components using same API, that means we have to write the same API consume code in all components.

Suppose, If any change in API consume 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 by angular components, directives and other services.

Advantages of Angular Services

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

How to Create Angular Service ?

If you have an angular application already,

You can create using 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 another components.

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

It creates as a singleton and shared class during runtime.

The service can be used as 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, Service class is declared in application module- app.module.ts

How service is created in global scope?

  • The service instance is created first time when 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 application module is destroyed or page is unloaded

Following are steps to configure global service

  • import Service in application module file - app.module.ts
  • Update Service class in providers section of NgModule

This registers as global service and 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

Local service can be configured in Components,Directive and pipes.

Here is the life cycle of local service

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

In this example, Service is injected in component itself, that means service instance is created during component creation.

Single component has a single copy of service instance.

  • Import Service class into component
  • Configure Service in provider attribute of @component metadata

@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 Realtime applications, Angular services are used for API operations like Create,Read, Update, Delete operations. 

Let's see CRUD operations for consuming API
Angular provides `HttpClient` service to consume external API's.

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

```javascript
import { NgModule } from '@angular/core';

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

@NgModule({
  declarations: [

  ],
  imports: [

    HttpClientModule
  ],
  providers: [],
  bootstrap: []
})
export class AppModule { }

Now you are able to use HttpClient service in your service.

Inject HttpClient in 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 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 difference between Service and a component

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

Let’s see some difference between them

Components   Service  
Components are UI to display on browser Services contains common functions for data processing logic
Can be created with @component decorator created with @Injectable decorator
Components can be independent or can use another component Services are used by across all components, can use other services
It contains reusable ui html functionality
It contains HTML,CSS, data binding logic Contains data process and access logic
component is not singleton, can have multiple instances Singleton instance across entire application

Conclusion

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

  • what is Angular service
  • How to create angular service
  • How to access services in Angular components
  • Angular global and local scope
  • Difference between service and component
  • Advantages of Angular services
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.