Angular 9 Service Tutorial: Creating API and HttpClient

Angular 9 Service Tutorial: Creating API and HttpClient

In this Angular 9 Service tutorial shows you the Angular Service example, we will create an API with HttpClient service. 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. Angular Service contains the various methods and functions to manage the data arriving from the server.

In this tutorial, we are going to discuss Angular 8/9 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.

Table of Contents

  • What is Angular Service?
  • Set Up Angular CLI
  • Setting Up Angular Project
  • Creating Service Class
  • Creating Methods in Service Class
  • Access Service Methods in Components
  • Conclusion

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/[email protected]

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.

import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { HttpClient, HttpHeaders, HttpErrorResponse } 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): Observable<any> {
    let API_URL = `${this.apiUrl}/create-task`;
    return, data)

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

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

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

  // 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(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.

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 8/9 Service 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.

Angular WebDev JavaScript

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Basics of Angular: Part-1

What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular. Angular is a Typesc

Upgrade Angular CLI from Angular 8 to Angular 9

In this Angular 9 tutorial is focused on upgrade Angular CLI to 9 in Ubuntu. This example will help you upgrade Angular CLI version for Angular 8 to Angular 9 globally. This article will give you simple example of update Angular 8 to 9. We will look at example of upgrade angular 8 to 9. Let's see bellow example update Angular CLI version 8 to 9.

How to Build an Angular Application with Angular CLI

How to set up the Angular CLI and generate a Trivial App

ReactJS vs Angular vs Vue: Best Javascript Framework For Your Project

ReactJS vs Angular vs Vue: Best Javascript Framework For Your Project. This video covers the key differences between ReactJS, Angular and Vue with respect to the following: Use case, Performance, Data binding, Scripting language, Testing, Community support, Growth curve

Learn Angular from Scratch and Go from Beginner to Advanced

In this Angular Tutorial, you'll learn Angular from scratch and go from beginner to advanced in Angular. In this Angular crash course you will learn from scratch. We will assume that you are a complete beginner and by the end of the course you will be at advanced level. This course contain Real-World examples and Hands On practicals.