Angular – HTTPClient POST Request Examples
In the last article, we already performed and followed the below steps which set up the prerequisites for using HttpClient in the Angular application. Today, we will see how to perform Angular – HTTPClient POST Request.
‘We will cover the below aspects for today’s article,
We shall now extend the previous article for HttpClient to invoke HTTP POST calls from the Angular applications.
Define HTTP Content-type Header
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
File: account.service.ts
addEmployee(emp: Employee): Observable<Employee> {
return this.http.post<Employee>(this.apiUrl, emp, this.httpOptions).pipe(
tap((emp: Employee) => this.log(`added emp = ${emp.Id}`)),
catchError(this.handleError<Employee>('addHero'))
);
}
File: login.component.ts
AddNewEmployee(Id: string): void {
if (!Id) { return; }
this.accountService.addEmployee({ Id } as Employee)
.subscribe(emp => {
this.emp = emp;
});
}
Connecting API/Service endpoint
You can now be ready to connect to any REST API endpoint.
I already have below API endpoint which we shall be returning as Employee model (which we have defined as Observable above in getEmployees()
I am using ASP.NET Core API below. However as we know REST API is language agnostic, you can use Spring, Node.js, Java or Python-based services, etc.
Let’s use the below Url, for now, to connect to REST API,
[HttpPost]
public ActionResult<Employee> Post([FromBody] Employee value)
{
//Add Employee to Database
CreateNewEmployee(value);
return Ok(value);
}
CORS on Server-side
Please note your Server should allow CORS requests from your Angular UI domain. Please visit for more details: How to Enable CORS in ASP.NET Core REST API
Once the CORS is enabled on your server side, you shall see the POST method hit your API and gives your required response.
Here is the HTML defined for LoginComponent ,
File: login.component.html
<h1>Hello TheCodeBuzz !! </h1>
<div>
<label>Add New Employee:
<input #empName />
</label>
<button (click)="AddNewEmployee(empName.value); empName.value=''">
Add New Employee
</button>
</div>
Finally, you can see the result on the browser,
If you haven’t done it already you need to update HttpClient in NgModule so that to be able to use it anywhere in your application
Add HttpClient to Service
Make HttpClient available in the app in two steps as explained below,
Step1: Register HttpClientModule in root Module as below,
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { LoggerService } from './logger.service';
import { AccountService } from './account.service';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent,
LoginComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [LoggerService,AccountService],
bootstrap: [AppComponent]
})
export class AppModule { }
Step2: DI HttpClient using Constructor Injection
To use HttpClient, you need to import below,
import { HttpClient, HttpHeaders } from '@angular/common/http';
Add HttpClient to EmployeeService using Constructor injections as below,
Here below is the complete code,
File:account.service.ts
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable, of } from 'rxjs'; import { catchError, map, tap } from 'rxjs/operators'; import { Employee } from './employee'; @Injectable({ providedIn: 'root' }) export class AccountService { private apiUrl = '/api/values'; constructor(private http: HttpClient) { } }
Summary
Today in this article we learned how to write simple Angular – an HTTP POST Request with easy-to-understand examples.
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.