Send Http Post with Angular 14 HttpClient by Example

WebTutPro
techiediaries.com
Published in
2 min readJan 31, 2020

Let’s see how to send an Http post request using HttpClient in Angular 14 by example.

✋✋ Join our Angular 14 Dev Community 👈 to discuss anything related to Angular 14 development.

Send Http Post with Angular 14 HttpClient by Example

The HttpClient post() Method

You can send Http post requests using the HttpClient.post method.

According to the Angular docs. This is the signature of this method:

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>

TheHttpClient.post method provides the following arguments:

  • url: the target server’s URL.
  • body: the data to be posted,
  • options: an optional argument used for headers, and parameters, etc.

The HttpClient.post method returns an RxJS Observable that you need to subscribe to in order to get the received data in the response.

Start by Importing HttpClientModule

Before you can use HttpClient methods including the post method, you need to first import and include HttpClientModule in your main application module:

import { HttpClientModule } from '@angular/common/http';@NgModule({
imports: [
HttpClientModule,
// [...]
],
// [...]
})
export class AppModule { }

We simply use the import statement to import the module from angular/common/http, and we include it in the imports array of the application module.

The app module can be found in the src/app/app/module.ts file.

Injecting the Angular HttpClient Service

After importing the HttpClientModule, you need to import inject the HttpClient service before you can send the post request.

First, import the service as follows:

import { HttpClient } from '@angular/common/http';

Next, inject HttpClient using the constructor as follows:

constructor(private httpClient: HttpClient) { }

You can either use HttpClient inside another service or directly in components in small or example apps.

Sending an Http Post Request

After making the previous steps, you can now send a post request to your backend server or third-party API service. For example, first we define a method as follows in our service/component:

sendPostRequest(data: any): Observable<any> {
return this.httpClient.post<any>(YOUR-SERVER-URL, data);
}

Next, you simply need to call the method and subscribe to the returned observable to actually send the Http post request to the server:

sendPostRequest(data).subscribe(
res => {
console.log(res);
}
);

--

--