make a http request with a custom body as form url encoded in typescript

To make an HTTP request with a custom body as form url encoded in Typescript, you can use the built-in HttpClient module. First, you’ll need to import the HttpClient module:

index.ts
import { HttpClient, HttpHeaders } from '@angular/common/http';
64 chars
2 lines

Assuming you want to make a GET request to an API with a custom body as form url encoded, you can do it like this:

index.ts
const body = new URLSearchParams();
body.set('key1', 'value1');
body.set('key2', 'value2');

const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');

this.httpClient.get('apiUrl', { headers, params: body.toString() }).subscribe(response => {
   // Handle the response here
});
313 chars
10 lines

Here, we have created a new instance of URLSearchParams and set the required key-value pairs to the body. Then, we have set the Content-Type header to application/x-www-form-urlencoded. Finally, we have passed the headers and the body to the HttpClient’s get method as options.

You can use post method instead of using get to send a post request with the same body data.

gistlibby LogSnag