Hello Devs,
In this tutorial, we are going to learn angular 10 http request example.
Here, we will talk about how to send http request in angular 10
Follow this step by step guide given below:
Create New App
ng new my-new-app
Import HttpClientModule
src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Create Service for API
ng g s services/post
src/app/services/post.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class PostService {
private url = 'http://jsonplaceholder.typicode.com/posts';
constructor(private httpClient: HttpClient) { }
getPosts(){
return this.httpClient.get(this.url);
}
create(post){
return this.httpClient.post(this.url, JSON.stringify(post));
}
}
Use Service to Component
src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { PostService } from './services/post.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
posts;
constructor(private service:PostService) {}
ngOnInit() {
this.service.getPosts()
.subscribe(response => {
this.posts = response;
});
}
createPost(input: HTMLInputElement){
let post = {title: input.value};
input.value = '';
this.service.create(post)
.subscribe((response: { id }) => {
post['id'] = response.id;
this.posts.splice(0,0, post);
});
}
}
Updated View File
src/app/app.component.html
<h1>Angular 10 HttpClient for Sending Http Request Example - HDTuto.com</h1>
<input
(keyup.enter)="createPost(title)" #title
type="text" class="form-control">
<ul class="list-group">
<li
*ngFor="let post of posts"
class="list-group-item">
{{ post.title }}
</li>
</ul>
Run this command:
ng serve
I hope this example helps you.