Important Update
The Guide Feature will be discontinued after December 15th, 2023. Until then, you can continue to access and refer to the existing guides.
Author avatar

Gaurav Singhal

Sending a Request and Processing a Mapped Response to Retrieve Data

Gaurav Singhal

  • Jul 17, 2019
  • 12 Min read
  • 172,345 Views
  • Jul 17, 2019
  • 12 Min read
  • 172,345 Views
Languages Frameworks and Tools
Angular

Introduction

The definition of request is “an act of asking for something, or the thing asked for”. Yes, if we are asking for something, we will get something from others. Like, If we give respect to others, then we will get respect from them. So many things happen in our daily lives. Like with animals, if you show love and care for your pet, then they also love you, care for you. The same thing will happen in our applications. When we make a request to do something, they return a response with some data. In this guide, we will look at how our application works with requests and responses. How will we handle responses with an application?

Speed up Application Development Using Angular 7

Angular is a JavaScript framework that allows you to be able to create reactive single-page applications. This is a leading front-end development framework that is regularly updated by the Angular team at Google. Angular 7 is entirely based on components.

Progressive Web Apps

We can use modern web platform capabilities to deliver app-like experiences: high performance, offline, and zero-step installation.

Universal

Angular 7 can serve the first view of your application on Node.js®, .NET, PHP, and other servers for near-instant rendering in just HTML and CSS.

Code Generation

Angular turns your templates into code that's highly optimized for today's JavaScript virtual machines, giving you all the benefits of hand-written code with the productivity of a framework.

Native

You can build native mobile apps with strategies from Cordova, Ionic, or NativeScript.

It is beneficial to understand the request and response process, so we are using an Angular 7 example to explain then throughout this guide.

Setup Angular to Explore Yourself

Before getting started with the guide, I will let you know we are using Angular 7 to handle HTTP. So, make sure you have Node.js in your system; if not, you can install it from here.

The next thing you need to do is to install Angular. Let's install it by npm.

1npm install -g @angular/cli
shell

Getting Started

The Http Client in @angular/common/HTTP offers a simplified client HTTP API for Angular applications that rests on the XMLHttpRequest interface exposed by browsers. Some additional benefits of HttpClient include testability features, typed request and response objects, request and response interception, Observable APIs, and streamlined error handling. We are using HttpClient to fetch data from the server to our application.

How Does Data Binding Happen in Angular 7?

There are two types of data binding in Angular 7:

One-way Data Binding

One-way data binding is a simple, one-way communication where the HTML template is changed when we make changes in the TypeScript code.

1import { Component } from "@angular/core";  
2@Component({  
3    selector: 'my-App',  
4    template: `  
5                <div>  
6                  <strong>{{name}}</strong>  
7                </div> `
8})
9
10export class AppComponent {  
11    name: string = "Sachin";  
12}
typescript

Two-way Data Binding

In two-way data binding, automatic synchronization of data happens between the Model and the View. Here, change is reflected in both components. Whenever you make changes in the Model, it will be reflected in the View, and when you make changes in View, it will be reflected in Model.

1import { Component } from '@angular/core';  
2  
3@Component({  
4    selector: 'my-app',  
5    template: `  
6                Enter the value  : <input [value]='name' (input)='name = $event.target.value'>  
7                <br>  
8                 Entered value : Hi  {{name}}  
9              `  
10})  
11export class AppComponent {  
12    name: string = '';  
13}  
typescript

What Is RxJS in Angular 7?

RxJS is a library for reactive programming that uses Observables to make it easier to compose asynchronous or callback-based code. This project is a rewrite of Reactive-Extensions/RxJS with better performance, better modularity, and better debuggable call stacks while staying mostly backward compatible with some breaking changes that reduce the API surface. In services, we import RxJS as given below to call the API.

1import * as Rx from "rxjs/Rx";
2import { from, Observable } from 'rxjs';
typescript

Jumping into the Code

Now that everything is installed on your system, let us jump into a simple example code.

Step 1: Start a New Project

Since Angular is a framework, we need to follow some standards of the framework. To create a new project in Angular, use command ng new project_name. I have named my project ResponseData_Binding.

1ng new ResponseData_Binding
shell

Step 2: Creating Our First Angular 7 Application for Request and Response

Setting up HttpClient The first step is to import the HttpClientModule in src/app/app.module.ts.

1import { HttpClientModule } from '@angular/common/http';
2@NgModule({
3    declarations: [
4        AppComponent
5    ],
6imports: [BrowserModule,HttpClientModule],
7bootstrap: [AppComponent]
8})
9export class AppModule { }
typescript

Next, lets create a class model. We’ll use command ng generate class class_name. I have named my class name users.

1ng generate class users
shell

After the class is generated, you’ll have to add objects:

1export class Users {
2    id:number;
3    email: string;
4    first_name: string;
5    last_name: string;
6}
typescript

For requests, we need to call the API for the service file that we need in Angular. Use the command ng generate service service_name. I have named the class name apicall.

1ng generate service apicall
shell

After you’ve generated apicall.service.ts, import the HTTP client, and initialized in the constructor, as given below.

1import { HttpClient } from '@angular/common/http';
typescript

In Constructor,

1constructor(private httpClient: HttpClient) {}
typescript

You can use the following command to run an Angular,.

1ng serve
shell

Step 3(a): Our First Requests to Get All List and Bind with Table

Angular defines a set of requests using request methods to indicate the desired action to be performed for a given resource.

To request to get all list of users, follow the below code steps:

apicall.service.ts

1import { Injectable } from '@angular/core';
2import { HttpClient } from '@angular/common/http';
3import { Users } from './users';
4import * as Rx from "rxjs/Rx";
5import { from, Observable, throwError } from 'rxjs';
6import { map, catchError } from 'rxjs/operators';
7@Injectable({
8  providedIn: 'root'
9})
10export class ApicallService {
11  constructor(private httpClient: HttpClient) {}
12  getUsers() {
13    return this.httpClient.get(`https://reqres.in/api/users`).
14        pipe(
15           map((data: Users[]) => {
16             return data;
17           }), catchError( error => {
18             return throwError( 'Something went wrong!' );
19           })
20        )
21    }
22}
typescript

In the above code, we created the getUsers() method to call the API. We are calling the HTTP GET method to get a list of all the users. We requested the API URL, https://reqres.in/api/users, to get a response map to the Users class using the map key. It will return a response and map to the object. If there are any exceptions then it will throw an error, “Something went wrong!”.

app.component.ts

1export class AppComponent {
2  
3  users : Users[];
4  
5  constructor(public http: HttpClient, private apiService: ApicallService){}
6
7  ngOnInit(){
8    this.getUserList();
9  }
10
11  getUserList() {
12    this.apiService
13    .getUsers()
14    .subscribe((data:any) => {
15      console.log(data);
16      this.users = data.data;
17    });
18  }
19}
typescript

In the above code, we created the getUserList() method. It is an action method, which is called at the ngOnInit() method. We use a ngOnInit() method to handle any additional initialization tasks and when the default change detector has checked the directive's data-bound properties for the first time. We called apiServices getUsers() to start calling the API.

app.component.html

1<table class="table table-striped">
2    <thead>
3        <tr>
4            <th>Email</th>
5            <th>First Name</th>
6            <th>Last Name</th>
7        </tr>
8    </thead>
9    <tbody>
10        <tr *ngFor="let user of users">
11            <td>{{user.email}}</td>
12            <td>{{user.first_name}}</td>
13            <td>{{user.last_name}}</td>
14        </tr>
15    </tbody>
16</table>
html

In the above code, we created a Table where we bind data to the table. We used for loop *ngFor="let user of users" where users have all lists of users and, by using for loop, we get a single value assigned to the row.

Step 3(a): Our First Requests to Send Detail to the Server

Follow the below code to send our data to the server using gPost.

apicall.service.ts

1import { Injectable } from '@angular/core';
2import { HttpClient } from '@angular/common/http';
3import { Users } from './users';
4import * as Rx from "rxjs/Rx";
5import { from, Observable, throwError } from 'rxjs';
6import { map, catchError } from 'rxjs/operators';
7
8@Injectable({
9  providedIn: 'root'
10})
11export class ApicallService {
12
13  constructor(private httpClient: HttpClient) {}
14
15  createUsers(user: Users[]) {
16    return this.httpClient.post(`https://reqres.in/api/users`,user).
17        pipe(
18           map((data: any) => {
19             return data;
20           }), catchError( error => {
21             return throwError( 'Something went wrong!' );
22           })
23        )
24    }
25}
typescript

In the above code, we used the createUsers() method to send our data to the server-side by using the POST Method. Here, we are requesting the API send our data to be saved to the server which is present in the user object. It returns a response and maps to the object. If there are any exceptions then it will throw an error, ”Something went wrong!”.

app.component.ts

1export class AppComponent {
2  
3  user: any = {};
4  
5  constructor(public http: HttpClient, private apiService: ApicallService){}
6
7  createUser(){
8    this.apiService.createUsers(this.user).subscribe((res)=>{
9    });
10  }
11}
typescript

In the above code, we created an action method, createUser(), where we called the createUsers() method from apiService and we pass the user object as a parameter.

app.component.html

1<form>
2  <input placeholder="Enter email" [(ngModel)]="user.email"/>
3  <input placeholder="Enter First Name"[(ngModel)]="user.first_name">
4  <input placeholder="Enter Last Name" [(ngModel)]="user.last_name"/>
5  <button type="submit" (click)="createUser()">Save</button>
6</form>
html

In the above code, we created a form where we fill in the data to be saved, the user object is collected from the input, and it is declared in app.component.ts. The ng-model directive binds the value of HTML controls (input, select, text area) to the application data. Using two-way binding, we can display a data property as well as update that property when the user makes changes.

Conclusion

Here are some of the ways that you can expand your code for learning purposes:

  • HttpClient simplified client HTTP API for Angular applications that rests on the XMLHttpRequest interface exposed by browsers.
  • Different ways of binding data in Angular.
  • Learn how to call API using HTTP Methods.
  • Data binding to the model.
  • Bind responses to the UI and model.
  • Create services to access API.

Now you should have an idea of how we request a response from the server.