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';

@Injectable({
  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';

@NgModule({
  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';

@NgModule({
  imports: [
    HttpClientModule
   ]
})

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';

@Injectable({
  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 this.http.post(API_URL, data)
      .pipe(
        catchError(this.error)
      )
  }

  // 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(
      catchError(this.error)
    )
  }

  // Delete
  deleteTask(id): 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}`;
    }
    console.log(errorMessage);
    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';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {

  constructor(private crudService: CrudService) { }

  ngOnInit() {
    console.log(this.crudService.showTasks);
  }

}

Conclusion

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 9 Tutorial: Learn to Build a CRUD Angular App Quickly

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

What’s new in HTML6

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

What is new features in Javascript ES2020 ECMAScript 2020

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

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

ReactJS, Angular and Vue have been all the craze the past couple of years. All these tools help developers build fancy user interfaces for web and mobile applications. But if all of them serve the same objective, what do you think makes them stand apart! Well, to address that, this video covers the key differences between ReactJS, Angular and Vue with respect to the following:

  1. Use case 03:11
  2. Performance 03:30
  3. Data binding 04:52
  4. Scripting language 06:05
  5. Testing 06:52
  6. Community support 07:31
  7. Growth curve 08:24

Learn Angular from Scratch and Go from Beginner to Advanced

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.

Complete Angular Course: Go From Zero To Hero

Complete Angular course. Learn Angular from scratch and go from beginner to advanced in Angular.

Welcome to this course "Complete Angular Crash Course: Learn Angular from Scratch and Go from Beginner to Advanced". In this 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. We will guide you step by step so that you can understand better. This course will allow you to work on the Real-World as a professional.

What you'll learn

  • Learn The Basics
  • Learn Advanced Methods
  • Step By Step Instructions So That You Can Go From Zero To Hero
  • A Complete Tutorial Explaining Everything You Need To Know
  • Real-World Examples With Hands On Tutorials
  • Get Answers To Your Every Single Questions

JavaScript Tutorial: if-else Statement in JavaScript

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.

JavaScript’s conditional statements:

  • if
  • if-else
  • nested-if
  • if-else-if

These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.

  • if: if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
    Syntax:
if(condition) 
{
   // Statements to execute if
   // condition is true
}

Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,

if(condition)
   statement1;
   statement2;

// Here if the condition is true, if block 
// will consider only statement1 to be inside 
// its block.

Flow chart:

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If statement 

var i = 10; 

if (i > 15) 
document.write("10 is less than 15"); 

// This statement will be executed 
// as if considers one statement by default 
document.write("I am Not in if"); 

< /script> 

Output:

I am Not in if
  • if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
    Syntax:
if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}


Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If-else statement 

var i = 10; 

if (i < 15) 
document.write("10 is less than 15"); 
else
document.write("I am Not in if"); 

< /script> 

Output:

i is smaller than 15
  • nested-if A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement. Yes, JavaScript allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
    Syntax:
if (condition1) 
{
   // Executes when condition1 is true
   if (condition2) 
   {
      // Executes when condition2 is true
   }
}

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate nested-if statement 

var i = 10; 

if (i == 10) { 

// First if statement 
if (i < 15) 
	document.write("i is smaller than 15"); 

// Nested - if statement 
// Will only be executed if statement above 
// it is true 
if (i < 12) 
	document.write("i is smaller than 12 too"); 
else
	document.write("i is greater than 15"); 
} 
< /script> 

Output:

i is smaller than 15
i is smaller than 12 too
  • if-else-if ladder Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
if (condition)
    statement;
else if (condition)
    statement;
.
.
else
    statement;


Example:

<script type = "text/javaScript"> 
// JavaScript program to illustrate nested-if statement 

var i = 20; 

if (i == 10) 
document.wrte("i is 10"); 
else if (i == 15) 
document.wrte("i is 15"); 
else if (i == 20) 
document.wrte("i is 20"); 
else
document.wrte("i is not present"); 
< /script> 

Output:

i is 20