Import HttpClientModule in the module file
We can import HttpClientModule from @angular/common/http in order to use the post method in our application.
import {HttpClientModule} from '@angular/common/http';@NgModule({......imports: [....HttpClientModule,....]...
)}
General Syntax for POST
As per official documents of angular, the post method is structured as given below
post(url: string, body: any | null, options: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe?: HttpObserve;
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType?: 'arraybuffer' | 'blob' | 'json' | 'text';
withCredentials?: boolean;
} = {}): Observable<any>
- URL- URL is the address to the server
- body -The body contains the data which we have to post on the server.
- headers -They represent the meta-data associated with the API request and response
- options -an optional argument used for headers, and parameters, etc.
Creating custom header
Here in the below code, we have created our custom header 'My-Custom-Header': 'foobar'
with predefined headers.
const headers = { 'Content-Type': 'application/json', 'My-Custom-Header': 'foobar' };
const body = { title: 'POST Request Example' };
this.http.post<any>('https://localhost:8080/posts', body, { headers }).subscribe(data => {
this.postId = data.id;
Creating a button to submit data
Here in the below example, emailFormControl
takes the data from the first input field and passwordFormControl
takes the value of password from the password field
<form class="example-form" (ngSubmit)="submitForm()">
......<input type="email" matInput [formControl]="emailFormControl" placeholder="Ex. pat@example.com"><input matInput [type]="hide ? 'password' : 'text'" matInput [formControl]="passwordFormControl" >
....
</form>
Create submit button
For activating submit button we define the post method as we have to submit data in JSON format we use the post method with headers as headers = {'Content-Type':'application/json'}
NOTE : My backend API is running on
http://localhost:8080/authenticate
url
const headers = { 'Content-Type': 'application/json' };let url = "http://localhost:8080/authenticate"this.http.post(url,{
"username" : this.emailFormControl.value,"password" : this.passwardFormControl.value},{headers}).toPromise().then((data:any)=>{console.log(data)})
.toPromise()
Notice that we call toPromise
in order to get from an Observable<Response>
to a Promise<Response>
We can check our Inspect element in a browser that Header data sent is received to the API.