Angular HTTP Request Tutorial Example
Angular HTTP Request Tutorial Example is today’s topic. Most of the front-end applications communicate with the backend services over an HTTP protocol. Modern browsers support two different APIs for making HTTP requests: the XMLHttpRequest
interface and the fetch()
API. With HttpClient
, @angular/common/http
provides a simplified API for HTTP functionality for use with Angular applications, building on top of the XMLHttpRequest
interface exposed by browsers.
Content Overview
Angular HTTP Request Tutorial
Here, I have used Angular CLI for the demonstration purpose.
Step 1: Do one Angular Project.
First, you need to install Angular CLI globally in your PC.
Then, go to the terminal and hit the following command.
ng new ngHTTPClient
So, it will create some boilerplates and also install all the NPM modules dependencies.
Step 2: Create a backend data.
If you have followed my Laravel 5.5 Angular 4 Tutorial Example From Scratch article then, in that section, I have described how to post the request data to the Laravel API server.
Now, For this example, I am using online JSON service to fetch the data from the server.
You can request the data to this URL: https://jsonplaceholder.typicode.com
Step 3: Include the HttpClient Module.
We need to include the module into the app.module.ts file.
// app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import {HttpClientModule} from '@angular/common/http'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Step 4: Making a request for JSON data.
// app.component.ts import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { // Inject HttpClient into your component or service. constructor(private http: HttpClient) {} ngOnInit(): void { // Make the HTTP request: this.http.get('https://jsonplaceholder.typicode.com').subscribe(data => { console.log(data); }); } }
The above code is perfect. And you will see the console output.
But in some cases, the output will not be there because of CORS problem.
You will find an error like this.
So, in the real-time application, if you are using Laravel or Node.js as a backend, you can find the solution by just download and install the right package for it.
If you are a Laravel developer then, you can find the solution on the above-mentioned link.
This is how you can get and post the request to any API server and get the response.
You can find more on this URL: https://angular.io/api/common/http/HttpClient
Finally, Our Angular HTTP Request Tutorial is over.