Angular 8 HttpClient Example | How To Send AJAX Request In Angular

Angular 8 HttpClient Example | How To Send AJAX Request In Angular

Angular 8 HttpClient Example | How To Send AJAX Request in Angular is today’s topic. Right now, the latest version of Angular framework is Angular 8.

Originally published by Krunal at appdividend.com

If you are new to Angular 8, then check out my Angular 8 Tutorial in this blog. Most front-end applications communicate with the backend services over an HTTP protocol. Modern browsers support the two different APIs for making HTTP requests.

  1. XMLHttpRequest interface and the 
  2. fetch() API.

We will use XMLHttpRequest for Angular application.

Content Overview
  • 1 Angular 8 HttpClient Example
  • 2 Angular HTTP module
  • 3 Setup Angular 8 Project
  • 4 Import HttpClientModule
  • 5 Create Service File
  • 6 Create a backend Server
  • 7 Send AJAX request to the server in Angular
  • 8 HTTP Headers
  • 9 HTTP PUT request in Angular
  • 10 HTTP PATCH request in Angular
  • 11 HTTP DELETE request in Angular
  • 12 HTTP POST request in Angular
Angular 8 HttpClient Example

The HttpClient in @angular/common/Http offers the simplified client HTTP API for Angular applications that rests on a XMLHttpRequest interface exposed by browsers. Additional benefits of the HttpClient include testability features, typed request and response objects, request and response interception, Observable apis, and streamlined error handling.

Angular HTTP module

The Angular HTTP module all have the RxJS Observable-based API. What this means is that the multiple calls to the HTTP module will all return the observable, that we need to subscribe to one way or the other way.

Here are some key points to bear in mind that a particular type of Observables returned by an HTTP module.

  1. If we don’t subscribe to the observables, nothing will happen.
  2. If we subscribe the multiple times to these observables, multiple HTTP requests will be triggered (see this post for more details).
  3. This particular type of Observables are the single-value streams: If an HTTP request is successful, these observables will emit only one value and then complete.
  4. These observables will emit the error if the HTTP request fails, more on this later.
Setup Angular 8 Project

We have already set up an Angular CLI, and now we need to create a project using the following command.

ng new ng8crud

It will create a new project and install the required files to set up the boilerplate.

Import HttpClientModule

Before you can use a HttpClient, you need to import an Angular HttpClientModule. Most apps do import in the root AppModule.

// app.module.ts

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

@NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
],
declarations: [
AppComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule {}

Create Service File

In Angular application, it is a best practice to create a service file related to a particular module.

If an angular app needs to interact with the back end server, then we can write the API calling code inside the service file.

So, if we need to send a POST request to the server, then we import the HttpClient inside the service file and make an AJAX request to the server with the data object. After a successful request, the server sends a response back to the client.

You typically post-process the data, add the error handling logic, and maybe some retry logic to cope with an intermittent connectivity.

The component quickly becomes cluttered with the data access. The component becomes harder to understand, even harder to test, and the data access logic can’t be re-used or standardized.

That’s why it is the best practice to separate presentation of the data from data access by encapsulating the data access in the separate service and delegating to that service in a component.

So, now create a service file by the following command.

ng g s config

Now, write the following code inside the config.service.ts file.

// config.service.ts

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

@Injectable()
export class ConfigService {
constructor(private http: HttpClient) { }
}

Create a backend Server

We need the fake data to work with and that is why I am using one package called json-server for this tutorial. Okay, so let us install the package using the Yarn package manager.

yarn global add json-server

or

npm install -g json-server

Now we need to create the folder inside src directory called data and in that folder, create one file called db.json. Let us add the following data inside the db.json file.

{
"characters": [
{
"id": "1",
"name": "Peter Dinklage",
"age": "45"
},
{
"id": "2",
"name": "Lina Heady",
"age": "43"
},
{
"id": "3",
"name": "Emilia Clarke",
"age": "30"
},
{
"id": "4",
"name": "Kit Harrington",
"age": "30"
},
{
"id": "5",
"name": "Sean Bean",
"age": "50"
}]
}

Now, start the JSON server using the following command.

json-server --watch src/data/db.json --port 4000

Now, we have the server running that can feed our data to our React Bootstrap Application.

Our JSON server is started at port: 4000 and URL is http://localhost:4000/characters.

Send AJAX request to the server in Angular

We have created a backend server and also created a service file.

Now, we need to write the code that sends a GET request to the json server.

So, write the following code inside the config.service.ts file.

// config.service.ts

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

@Injectable()
export class ConfigService {
constructor(private http: HttpClient) { }
url = 'http://localhost:4000';
getCharacters() {
return this
.http
.get(${this.url}/characters);
}
}

And here is the example of a small service that queries the database above using an HTTP GET, and fetch the data. This data then goes to the related component and using HTML, and we can show the data on the screen.

The above example is using the HTTP module in a small service file, that is displaying a list of characters. Let’s break down the following example step-by-step:

  1. We are using the new HttpClient client module, and injecting it in the constructor/
  2. Then we are calling the get() method, which is returning the data.

The HttpClient.get() method parsed a JSON server response into an anonymous Object type. It doesn’t know what a shape or attributes of that object is.

You can tell the HttpClient the type of response to make consuming the output easier and more prominent.

First, define the interface with the Characters attribute.

export interface Characters {
id: Number;
name: String;
age: Number;
}

Then, specify that interface as an HttpClient.get() call’s type parameter in the service.

HTTP Headers

If we want to add the custom HTTP Headers in our HTTP request then, in addition to the headers the browser already attaches automatically. We can do this by using the HttpHeaders class.

const headers = new HttpHeaders()
.set("X-CustomHeader", "custom header value");

getCharacters() {
return this
.http
.get(${this.url}/characters, {headers}); }

As we can see, HttpHeaders also has an immutable API, and we are passing a configuration object as the second argument of the get() call.

This configuration object only has one property named headers, just like the local const that we defined – so we used the object short-hand creation notation to describe the configuration object.

HTTP PUT request in Angular

Just like in the case of GET request, we can also use the Angular HTTP Client to do all the other available HTTP methods, namely the methods typically used for data modification such as PUT.

The PUT method should only be used if we want to replace the value of the resource.

HTTP PATCH request in Angular

Most often than not, instead of providing the complete new version of the resource, what we want to do is to update a single property. And this is the primary use case for the use of the HTTP PATCHmethod.

The PATCH request is useful in situations where there is some further server-side modification of the patched values, such for example via a database trigger or a Firebase rule.

HTTP DELETE request in Angular

Another frequent operation that we want to do is to trigger the logical delete of some data. This operation can completely wipe the data from our database or mark some data as deleted.

HTTP POST request in Angular

If the operation that we are trying to do does not fit the description of any of the methods above (GET, PUT, PATCH, DELETE), then we can use an HTTP wildcard modification operation: POST.

That operation is typically used to add the new data to the database, although there are many other use cases.

Finally, Angular 8 HttpClient Example | How To Send AJAX Request in Angular is over.

Originally published by Krunal at appdividend.com

==========================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Angular 8 (formerly Angular 2) - The Complete Guide

☞ Complete Angular 8 from Zero to Hero | Get Hired

☞ Learn and Understand AngularJS

☞ The Complete Angular Course: Beginner to Advanced

☞ Angular Crash Course for Busy Developers

☞ Angular Essentials (Angular 2+ with TypeScript)

☞ Angular (Full App) with Angular Material, Angularfire & NgRx

☞ Angular & NodeJS - The MEAN Stack Guide

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Hire Now: https://bit.ly/394wdOx

Important reasons for developers to adopt Angular JS development

 Important reasons for developers to adopt Angular JS development

In the current scenarios, e-commerce companies are very keen to create an online impact. The web and app development market are at its peak of popularity. There is a high demand for web and app developers with a growing number of websites. Angular...

In the current scenarios, e-commerce companies are very keen to create an online impact. The web and app development market are at its peak of popularity. There is a high demand for web and app developers with a growing number of websites. Angular has been a top choice for web development and it's the latest version AngularJS has gained popularity in the industry. This java script framework has created its prominent position in creating web apps.
Regardless of whether there are numerous different systems accessible for web development, AngularJS can support among them all. Since its introduction in the market, Angular has been creating waves in the market.

Introduction

Angular js is a powerful framework that was developed by Google. It is used to build dynamic apps with power-packed features. It was first introduced in 2010 and created by developers at Google. This framework was created to simplify and remove the challenges in creating dynamic apps. It uses HTML, CSS, and java script to create dynamic single-page applications. Angular Js is inclusive of Mongo DB and it is a frontend fragment of Mean Stack. In the developer's community, Angular is considered as a reliable and fast Java script framework. Many popular apps like PayPal. You tube, Netflix, the guardian, Lego are built using the AngularJS framework.

In this blog, we are listing some compelling reasons to pick angular development to familiarize you with its potential

• Open-source framework: It is not a library but open-source frameworks that enable the developers to build well-performing single page web applications. Just after its launch, it became hugely popular among the developers and it is not going to come at a halt.

• Simplified MVC structure: Developers use AngularJS to build robust and interactive web applications. AngularJS framework uses MVC architecture to create interactive applications. AngularJS makes it easy for developers to create apps as they are only required to split the applications.

• Extensive community: As angular is built by Google, it is backed by a very large community of professionals. The Angular JS conferences of the professionals are held all over the world. Hackathons are also organized in IT communities that include some professional and skilled engineers who can help with the queries and questions related to Angular.

• Declarative code system: In Angular JS developers can create declarative patterns by using declarative paradigms. It enables developers to be less heavy, and easy to read. In this framework, the developers get data models that are not too complex to write that abolishes the need to use any getter/setters and with easy data manipulation.

• Two-way data binding: It is one of the impeccable features that makes Angularjs popular in the developers' community. It allows seamless projections of the models and data binding. In this framework, any changes in the user interface make an impact on the application objects. The developers are not required to fresh the cycle and that makes it vulnerable to bugs.

• Using directives: AngularJS makes use of Directives as the developers can build custom HTML tags that function as custom widgets and it can be possible using directives. Its implications are also in the case of the use of decorating components and manipulation of DOM elements in appealing ways.

• Enterprise-level testing: When using Angular JS there is no need for demanding any other supplementary framework or additional plugins. In the process, parts of applications are put in the angular framework which is not too complex for manipulation. In module separation, developers can load essential services in an effective way for the performance of automatic testing.

• Client-side situation: AngularJS mainly works at the client-side and it is fully compatible with both web and mobile browsers. It can function with any projects without the need for any backend notifications. The developers can easily use AngularJS for the front end of applications.

• Easy to use: AngularJS is rich with its features and facilitates developers to reduce any need for writing codes. It reduces the burden of developers by the application of MVC architecture and data models.

Many other significant features make AngularJS prioritize by the developers than other Javascript frameworks. The above-mentioned reasons have made it the top choice for reputed companies all across the globe for web development. Developers at the company master the skills to work with Angular JS development for web. The company is equipped with dedicated professionals having sound technical knowledge of working with AngularJS. We offer offshore services to extend our reach all across the globe with various models. We have more than 15 years of experience in the industry that we use to deliver high-quality solutions by leveraging the latest technology and quality standards.

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company