Consume REST API
Step 8 β Consuming the JSON REST API with Angular HttpClient 13β
In this step, we'll proceed to consume JSON data from our REST API server in our example application.
We'll need to create an Angular service for encapsulating the code that deals with consuming data from the REST API server.
A service is a singleton that can be injected by other services and components using the Angular dependency injection.
In software engineering, dependency injection is a technique whereby one object supplies the dependencies of another object. Source
Now, letβs generate an Angular service that interfaces with the JSON REST API. Head back to your command-line interface and run the following command:
$ ng generate service data
Next, open the src/app/data.service.ts
file, import and inject HttpClient
as follows:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
private REST_API_SERVER = "<http://localhost:3000>";
constructor(private httpClient: HttpClient) { }
}
We imported and injected the [HttpClient
service](https://www.techiediaries.com/angular-http-client/) as a private httpClient
instance. We also defined the REST_API_SERVER
variable that holds the address of our REST API server.
Next, add a sendGetRequest()
method that sends a GET request to the REST API endpoint to retrieve JSON data:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
private REST_API_SERVER = "<http://localhost:3000>";
constructor(private httpClient: HttpClient) { }
public sendGetRequest(){
return this.httpClient.get(this.REST_API_SERVER);
}
}
The method simply invokes the get()
method of HttpClient
to send GET requests to the REST API server.
Next, we now need to use this service in our home component. Open the src/app/home/home.component.ts
file, import and inject the data service as follows:
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
products = [];
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.sendGetRequest().subscribe((data: any[])=>{
console.log(data);
this.products = data;
})
}
}
We imported and injected DataService
as a private dataService
instance via the component constructor.
Next, we defined a products
variable and called the sendGetRequest()
method of the service for fetching data from the JSON REST API server.
Since the sendGetRequest()
method returns the return value of the HttpClient.get()
method which is an RxJS Observable, we subscribed to the returned Observable to actually send the HTTP GET request and process the HTTP response.
When data is received, we added it in the products
array.
Next, open the src/app/home/home.component.html
file and update it as follows:
{% raw %}
<div style="padding: 13px;">
<mat-spinner *ngIf="products.length === 0"></mat-spinner>
<mat-card *ngFor="let product of products" style="margin-top:12px;">
<mat-card-header>
<mat-card-title>{{product.name}}</mat-card-title>
<mat-card-subtitle>{{product.price}} $/ {{product.quantity}}
</mat-card-subtitle>
</mat-card-header>
<mat-card-content>
<p>
{{product.description}}
</p>
<img style="height:100%; width: 100%;" src="{{ product.imageUrl }}" />
</mat-card-content>
<mat-card-actions>
<button mat-button> Buy product</button>
</mat-card-actions>
</mat-card>
</div>
{% endraw %}
We used the <mat-spinner>
component for showing a loading spinner when the length of the products
array equals zero i.e before no data is received from the REST API server.
Next, we iterated over the products
array using [ngFor](https://www.techiediaries.com/angular-ngfor/)
and used a Material card to display the name
, price
, quantity
, description
and image
of each product.
This is a screenshot of the home page after JSON data is fetched:
Next, we'll see how to add error handling to our service.