Angular 10 Tutorial - HttpClient
In this tutorial, we are going to learn about HttpClient in Angular 10. HttpClient helps us fetch external data and post data. It is a simplified client HTTP API for Angular 10 applications. Additional benefits of HttpClient include testability features, typed request and response objects, request and response interception, Observable APIs, and streamlined error handling.
Importing HttpClientModule
Now, let's see how we can use HttpClient in Angular 10. Before using the HttpClient, we need to import the Angular HttpClientModule in app.module.ts. So, let's import this:
Switch to the project and open the app.module.ts file. And in this file, just write:
import { HttpClientModule } from '@angular/common/http';
Also, add inside the imports array, so just write:
imports: [
BrowserModule,
HttpClientModule
],
Creating a New Component
Now, let's create a new component. So, switch to the command prompt and just write:
ng g c components/blog
Now, just open the blog.component.ts file and inside this file, import HttpClient first:
import { HttpClient } from '@angular/common/http';
Now, inside the constructor, just write:
constructor(private http: HttpClient) { }
Now, inside the ngOnInit function, just write:
ngOnInit() {
this.http.get("").
subscribe((data) ⇒ console.log(data))
}
Using Jsonplaceholder API
Here, we will use the Jsonplaceholder API to understand the HttpClient. So, go to google.com and just search for Jsonplaceholder. Now, just open the first link. This is a fake REST API. In this page, just click on this link. You can see here the hundreds of posts. Now, just copy this URL and paste here:
ngOnInit() {
this.http.get("https://jsonplaceholder.typicode.com/posts").
subscribe((data) ⇒ console.log(data))
}
Configuring Routing
Now, let's add a route. So, just open the app-routing.module.ts file and here, import the BlogComponent:
Import {BlogComponent} from './components/blog/blog.component';
Now, add the route here:
{
path:'blog',
component:'blogcomponent'
}
Displaying Blog Posts
Now, go to the app.component.html file and add a link into the navbar. Just copy this and paste here. Now, change the text here.
Alright, now let's check it. Switch to the browser and just click on the blog link. And open the console, and here you can see the blog posts. Now, let's display this post here. So, just open the blog.component.ts file and here, just create a property:
posts;
Now, create a function here:
displaydata(data)
{
this.posts = data;
}
Now, add this function here:
subscribe((data) => this.displaydata(data));
Now, go to the blog.component.html file and add the following:
<div *ngFor="let post of posts ">
<h3>{{post.title}}</h3>
<p>{{post.body}}</p>
</div>
Testing HttpClient
Now, let's check it. So, switch to the browser, and here you can see all hundred posts. So, in this way, you can use HttpClient in Angular 10.