This post is from a low-reputation account and contains an unverified outbound link. Be cautious before clicking external links.

Angular 9/8 How-To: Create a Service with HttpClient

Words
311
Reading
2 min
Listen
Play
7y

In this tutorial, we'll learn how to use HttpClient to build a service for connecting your Angular application to a REST API server.

We'll see how to implement an Angular service to encapsulate the code that handles fetching data from the REST API server.

An Angular service is simply a TypeScript class that you can inject in other services or components using the Angular dependency injector.

Prerequisites

You need to have Node, NPM and Angular CLI and initialized an Angular project.

Step 1 - Importing HttpClient Module

Open the src/app/app.module.ts file and update as follows:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 2 - Creating an Angular Service

Open a new terminal and run the following command:

$ ng generate service backend

Step 3 - Importing and Injecting HttpClient

Open the src/app/backend.service.ts file, then import and inject HttpClient as follows:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class BackendService {

  constructor(private httpClient: HttpClient) { }
}

We import HttpClient and inject it via the service constructor.

Step 4 - Defining a Method for Sending HTTP Requests

Next, define a get() method for sending a GET request to the server for fetching data:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class BackendService {

  constructor(private httpClient: HttpClient) { }

  public get(){
    return this.httpClient.get("http://server.com/endpoint");
  }
}

We call the get() method of HttpClient to send a GET request to the REST API server.

Step 5 - Creating an Angular Component

Head back to your terminal and run the following command to generate a component named home:

$ ng generate component home

Step 6 - Injecting the Angular Service

Go to the src/app/home/home.component.ts file, import and inject the backend service as follows:

import { Component, OnInit } from '@angular/core';
import { BackendService } from '../backend.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  data= [];

  constructor(private backendService: BackendService) { }

}

Step 7 - Calling the Service Method

Finally, we can call the get() method of the service to send a GET request as follows:

  ngOnInit() {

    this.backendService.get().subscribe((ret: any[])=>{
      console.log(ret);
      this.data = ret;
    })  
  }

Step 8 - Displaying Data with ngFor

Next, open the src/app/home/home.component.html file and update it as follows:

<div>
<ul>
    <li *ngFor="let item of data">
        {{item.name}}
    </li>
</ul>           
</div>

Here, we suppose that our data elements have a name attribute.

Conclusion

In this how-to post, we've seen how to create a service in Angular and use HttpClient to send HTTP requests to REST API backends and finally display the data returned from the API using the ngFor directive.

Angular 9/8 How-To: Create a Service with HttpClient | Ecency