Angular 8/9 Service Tutorial with Example

Last updated on by Digamber
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.

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

@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.

Digamber
Digamber

Digamber Rawat is From Uttarakhand, land of Gods located in northwestern part of India. He is a Data Scientist by profession and a primary author of this blog.