Angular 9/8 How-To: Pass URL Query Parameters with HttpClient, HttpParams and fromString
In this post we will give you information about Angular 9/8 How-To: Pass URL Query Parameters with HttpClient, HttpParams and fromString. Hear we will give you detail about Angular 9/8 How-To: Pass URL Query Parameters with HttpClient, HttpParams and fromStringAnd how to use it also give you demo for it if it is necessary.
In this how-to article, we’ll learn how to use fromString
and HttpParams
to pass query parameters to URLs or REST API endpoints.
Here, we assume we have a REST API endpoint named server.com/api/products
with _page
and _limit
parameters.
We also assume, you have an Angular 9 project with the HttpClientModule
imported in the main module or the module where you are implementing the requirement.
If you are new to these how-tos, check out how to install and set up a project and the prerequisites.
Step 1 – Generating and Implementing an Angular 9 Example Service
Head back to your terminal, navigate to your project’s directory and run the following command to generate an Angular service:
$ ng generate service example
Next, open the src/app/example.service.ts
file and update it as follows:
import{Injectable}from'@angular/core';import{HttpClient,HttpErrorResponse}from"@angular/common/http";@Injectable({providedIn:'root'})exportclassExampleService{constructor(privatehttpClient:HttpClient){}}
We import HttpClient
and inject it via the service constructor.
Step 2 – Importing the Angular 9 HttpParams Interface
Next, import HttpParams
in the src/app/example.service.ts
file as follows:
import{HttpParams}from"@angular/common/http";
Step 3 – Sending a GET Request with Parameters
Next, define the sendGetRequestWithHttpParameters()
method as follows:
publicsendGETRequestWithParameters(){constopts={params:newHttpParams({fromString:"_page=1&_limit=10"})};returnthis.httpClient.get("http://server.com/api/products",opts);}
We create an instance of HttpParams
from the ‘page=1&limit=10string using
fromString. This way we pass the value of 1 to the
pagequery parameter and 10 to
limit’ query parameter.
You can also use the append()
method of HttpParams
to set and pass parameters:
publicsendGETRequestWithParameters(){'''letparams=newHttpParams();params=params.append('_page',1);params=params.append('_limit',10);returnthis.httpClient.get("http://server.com/api/products",{params:params});}
Hope this code and post will helped you for implement Angular 9/8 How-To: Pass URL Query Parameters with HttpClient, HttpParams and fromString. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs