Angular 16 Service Tutorial with Example

Last Updated on by in Angular
In this Angular 16 Service example guide, we are going to discuss Angular Service. To show you the Angular Service example, we will create API with HttpClient service.Angular Service contains the various methods and functions to manage the data arriving from the server.

Why Angular Service Class?

  • To handle the features that are separate from components such as authentication, CRUD operations.
  • To share the data among various components in an Angular app.
  • To make the Testing and Debugging simple.
  • To write the re-usable code to centrally organise the application.

To sharpen your skills in Angular, check out the following Angular tutorials.

What is Angular Service?

Most of the time, we get into the situation where we need to use the same code again and again. Using repetitive code in multiple components becomes a headache.

When the size of an Angular application gets bigger, then It almost becomes difficult to manage the code base of our app. In this scenario, the best practice will be to write the reusable code.

To deal with this kind of situation, we can undoubtedly take the help of the Services class in Angular. Its a JavaScript class and includes properties and methods to share the data between unknown components classes.

Set Up Angular CLI

To install the Angular project, you need to have latest version of Angular CLI installed.

npm install -g @angular/cli@latest

In case of error prefix `sudo` with the above command and provide admin password.

Setting Up Angular Project

Run the below command to install the brand new Angular project.

ng new angular-service-example

Run command to get inside the project folder.

cd angular-service-example

Start the application in the browser.

ng serve --open

Creating Service Class

Our service will contain the create, read, update and delete methods for a demo task management app. To create an Angular Service class, you need to run the following command via Angular CLI.

ng generate service crud

Above command creates the following files in the src/app folder.

# src/app/crud.service.spec.ts

# src/app/crud.service.ts

Here, is the file crud.service.ts file we generated for Angular Service example.

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

  providedIn: 'root'

export class CrudService {

  constructor() { }

@Injectable(): Decorator that marks a class as available to be provided and injected as a dependency.

providedIn: Injectors make the communication with injectable that is something based on with @NgModule or other InjectorType, even by specifying that this injectable should be provided in the ‘root’ injector.

Next, we need to import the Service Class in the app.module.ts, and also register the service class in the providers array.

// Service class
import { CrudService } from './crud.service';

  declarations: [...],
  imports: [...],
  providers: [CrudService],
  bootstrap: [...]

Importing and registering the service class in Angular’s main app module means that, service class is available throughout the application.

Creating Methods in Service Class

In this part of the tutorial, we will write API in Angular Service Class. In the below example we wrote the CRUD operations using the HttpClient service.

To make these methods work you also need to import and register HttpClientModule in the main app module file.

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

  imports: [

In the API section you need to pass the API URL in order to make this API work. Make sure to update the code in crud.service.ts file.

import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import {
} from '@angular/common/http';

  providedIn: 'root',
export class CrudService {
  apiUrl: string = 'enter-your-api-url';
  headers = new HttpHeaders().set('Content-Type', 'application/json');

  constructor(private http: HttpClient) {}

  // Create
  createTask(data: any): Observable<any> {
    let API_URL = `${this.apiUrl}/create-task`;
    return, data).pipe(catchError(this.error));

  // Read
  showTasks() {
    return this.http.get(`${this.apiUrl}`);

  // Update
  updateTask(id: any, data: any): Observable<any> {
    let API_URL = `${this.apiUrl}/update-task/${id}`;
    return this.http
      .put(API_URL, data, { headers: this.headers })

  // Delete
  deleteTask(id: any): Observable<any> {
    var API_URL = `${this.apiUrl}/delete-task/${id}`;
    return this.http.delete(API_URL).pipe(catchError(this.error));

  // Handle Errors
  error(error: HttpErrorResponse) {
    let errorMessage = '';
    if (error.error instanceof ErrorEvent) {
      errorMessage = error.error.message;
    } else {
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    return throwError(() => {
      return errorMessage;

Access Service Methods in Components

To access the Service methods, we need to import the Service in the component file, let’s import the CrudService class in the app.component.ts.

import { CrudService } from './crud.service';

Next, we need to follow the dependency injection pattern and inject the Service class inside the constructor.

export class AppComponent {

  constructor(private crudService: CrudService){}


Next, we can easily access all the CrudService methods, and we are using the ngOnInit() lifecycle hook to access the showTask() method of Angular Service class.

Update code in app.component.ts file.

import { Component, OnInit } from '@angular/core';
import { CrudService } from './crud.service';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']

export class AppComponent implements OnInit {

  constructor(private crudService: CrudService) { }

  ngOnInit() {



Now, Angular Service example tutorial is completed with examples. In this tutorial, we looked at how to create a Service class and write the APIs in it.

We also learned how to access the Service methods and properties in Angular components.

I hope you liked this tutorial. Please share this tutorial with others.

Digamber - Author

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.