Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Sending a Request and Processing a Mapped Response to Retrieve Data

Jul 17, 2019 • 12 Minute Read

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.

      npm install -g @angular/cli
    

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.

      import { Component } from "@angular/core";  
@Component({  
    selector: 'my-App',  
    template: `  
                <div>  
                  <strong>{{name}}</strong>  
                </div> `
})

export class AppComponent {  
    name: string = "Sachin";  
}
    

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.

      import { Component } from '@angular/core';  
  
@Component({  
    selector: 'my-app',  
    template: `  
                Enter the value  : <input [value]='name' (input)='name = $event.target.value'>  
                <br>  
                 Entered value : Hi  {{name}}  
              `  
})  
export class AppComponent {  
    name: string = '';  
}
    

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.

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

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.

      ng new ResponseData_Binding
    

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.

      import { HttpClientModule } from '@angular/common/http';
@NgModule({
    declarations: [
        AppComponent
    ],
imports: [BrowserModule,HttpClientModule],
bootstrap: [AppComponent]
})
export class AppModule { }
    

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

      ng generate class users
    

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

      export class Users {
    id:number;
    email: string;
    first_name: string;
    last_name: string;
}
    

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.

      ng generate service apicall
    

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

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

In Constructor,

      constructor(private httpClient: HttpClient) {}
    

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

      ng serve
    

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

      import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Users } from './users';
import * as Rx from "rxjs/Rx";
import { from, Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})
export class ApicallService {
  constructor(private httpClient: HttpClient) {}
  getUsers() {
    return this.httpClient.get(`https://reqres.in/api/users`).
        pipe(
           map((data: Users[]) => {
             return data;
           }), catchError( error => {
             return throwError( 'Something went wrong!' );
           })
        )
    }
}
    

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

      export class AppComponent {
  
  users : Users[];
  
  constructor(public http: HttpClient, private apiService: ApicallService){}

  ngOnInit(){
    this.getUserList();
  }

  getUserList() {
    this.apiService
    .getUsers()
    .subscribe((data:any) => {
      console.log(data);
      this.users = data.data;
    });
  }
}
    

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

      <table class="table table-striped">
    <thead>
        <tr>
            <th>Email</th>
            <th>First Name</th>
            <th>Last Name</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let user of users">
            <td>{{user.email}}</td>
            <td>{{user.first_name}}</td>
            <td>{{user.last_name}}</td>
        </tr>
    </tbody>
</table>
    

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

      import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Users } from './users';
import * as Rx from "rxjs/Rx";
import { from, Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

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

  constructor(private httpClient: HttpClient) {}

  createUsers(user: Users[]) {
    return this.httpClient.post(`https://reqres.in/api/users`,user).
        pipe(
           map((data: any) => {
             return data;
           }), catchError( error => {
             return throwError( 'Something went wrong!' );
           })
        )
    }
}
    

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

      export class AppComponent {
  
  user: any = {};
  
  constructor(public http: HttpClient, private apiService: ApicallService){}

  createUser(){
    this.apiService.createUsers(this.user).subscribe((res)=>{
    });
  }
}
    

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

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

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.