URL Parameters And Query Parameters In Angular HttpClient
In this article, we will learn how to use Angular to pass URL or Query parameters along with HTTP requests. The URL parameter will be added using HttpParams, which will then be used by the GET, POST, PUT, and PATCH methods to submit an HTTP request to the back-end API. Query strings, Query parms, Get parms, and more names for URL parameters exist.
The URL Parameters
We constructed a GitHubService in the Angular HttpClient GET Example article. The Service sent a GET request to the GitHub API Endpoint to get a list of repositories owned by a specific user.
The GitHub API also has a range of parameters that let us indicate how we want to sort, which page to retrieve, the number of entries per page, and the type of repository to retrieve, among other things.
As an example,
https://api.github.com/users/jigneshpatel0748/repos?sort=description&page=2
HttpParams()
import { HttpClient,HttpParams } from '@angular/common/http';
Create a new instance of the HttpParams class after that.
const params = new HttpParams() .set('page', PageNo) .set('sort', SortOn);
Then invoke the httpClient.get The params are passed as an argument to the get method.
return this.httpClient.get<repos[]>(this.baseURL + 'users/' + userName + '/repos',{params})
The methods accessible in the HttpParams class are listed below.
HttpParams.set
set(param: string, value: string): HttpParams
params = new HttpParams() .set('page', '2') .set('page', '3') .set('sort', 'name'); console.log(params.toString()); //Returns page=3&sort=name
HTTPParams is immutable
let params = new HttpParams(); params.set('page', PageNo); params.set('sort', SortOn);
let params = new HttpParams() .set('page', PageNo) .set('sort', SortOn);
You could also try this.
let params = new HttpParams(); params=params.set('page', PageNo); params=params.set('sort', SortOn);
HttpParams.append
append(param: string, value: string): HttpParams
Create a new body with the supplied parameter name's value appended. Regardless of whether the parameter exists, the value is always appended. In the following example, the page parameter is appended twice.
params = new HttpParams() .set('page', '2') .append('page', '3') .set('sort', 'name'); console.log(params.toString()); //Returns page=2&page=3&sort=name
let params = new HttpParams(); params=params.append('page', PageNo); params=params.append('sort', SortOn);
HttpParams.has
has(param: string): boolean
If the specified parameter name already exists in the HttpParams, returns true.
params = new HttpParams() .set('sort', 'name'); if (!params.has('page')) { params = params.set('page', PageNo) }
HttpParams.get
get(param: string): string | null
Get the initial value for the specified parameter name, or null if none exists.
params = new HttpParams() .set('page', '2') .append('page', '3') .set('sort', 'name'); console.log(params.get('page')); // Returns 2 The First occurance of Page
HttpParams.getAll
getAll(param: string): string[] | null
Returns all values for the provided parameter name, or null if the parameter isn't present.
params = new HttpParams() .set('page', '2') .append('page', '3') .set('sort', 'name'); console.log(params.getAll('page')); // Returns ["2", "3"] All occurance of Page
HttpParams.keys
keys(): string[]
Get a list of all the parameters for this body.
let params = new HttpParams() .set('page', '2') .set('sort', 'name'); console.log(params.keys()); //Returns ["page", "sort"]
HttpParams.delete
delete(param: string, value?: string): HttpParams
Returns the new parameter collection after deleting the parameter. You can delete a parameter by providing the name or the name and value. All parameters are erased if no argument is supplied.
params = new HttpParams() .set('page', '2') .Append('page', '3') .set('sort', 'name'); params = params.delete('page', '3'); //Deletes the parameter page with value 3 params = params.delete('page'); //Delete the all the parameter of page params = params.delete(''); //Delete all parameters
HttpParams.toString
toString(): string
Serialize the body to an encoded string, with &s separating key-value pairs (separated by =).
params = new HttpParams() .set('page', '2') .Append('page', '3') .set('sort', 'name'); console.log(params.toString()); //Returns page=2&page=3&sort=name
HTTP Parameters from a string
let params = new HttpParams({fromString: 'page=' + PageNo + '&sort=' + SortOn});
HTTP Parameters from an object
let params = new HttpParams({ fromObject: { page: PageNo, sort: SortOn } });
Without params
//You an also do it this way. return this.httpClient.get<repos[]>(this.baseURL + 'users/' + userName + '/repos?'+'page='+PageNo+'&sort='+SortOn);
Angular Httpparams Example
import {HttpClientModule} from '@angular/common/http';
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule, FormsModule ], providers: [GitHubService], bootstrap: [AppComponent] })
Passing the URL Parameters
import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { repos} from './repos'; import { Observable } from 'rxjs';
HttpClient should be injected into the Constructor.
constructor(private httpClient:HttpClient){ }
Create the params object in the GetRepos method.
const params = new HttpParams() .set('page', PageNo) .set('sort', SortOn);
When calling the httpClient, use the params. as demonstrated in the example below:
return this.httpClient.get<repos[]>(this.baseURL + 'users/' + userName + '/repos',{params})
The following code is the complete code of the github.service.ts file.
import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { Observable} from 'rxjs/Rx'; import { repos} from './repos'; @Injectable() export class GitHubService { baseURL= "https://api.github.com/"; constructor(private httpClient: HttpClient){ } getRepos(userName: string, PageNo: string, SortOn: string): Observable<repos[]> { let params = new HttpParams() .set('page', PageNo) .set('sort', SortOn); console.log(params.toString()); return this.httpClient.get<repos[]>(this.baseURL + 'users/' + userName + '/repos', {params}); } }
The following code is the complete code of the App.component.ts file.
import { Component } from '@angular/core'; import { Observable} from 'rxjs/Rx'; import { GitHubService } from './github.service'; import { repos} from './repos'; @Component({ selector: 'app-root', templateUrl: './app.component.html', }) export class AppComponent { userName = 'tekarticleshub'; pageNo = '1'; sortOn = 'description'; repos: repos[]; loading = false; errorMessage = ''; constructor(private githubService: GitHubService) { } public getRepos() { this.loading = true; this.errorMessage = ''; this.githubService.getRepos(this.userName,this.pageNo,this.sortOn) .subscribe((response) => {this.repos = response;}, (error) => { this.errorMessage = error.message; this.loading = false; }, () => {this.loading = false;}) } }
The following code is the complete code of the App.component.html file.
<div class="container"> <h1 class="heading"><strong>HTTP </strong>Demo</h1> <div class="form-group"> <label for="userName">User Name</label> <input type="text" class="form-control" name="userName" [(ngModel)]="userName"> <label for="pageNo">Page No</label> <input type="text" class="form-control" name="pageNo" [(ngModel)]="pageNo"> <label for="sortOn">Sorted On</label> <input type="text" class="form-control" name="sortOn" [(ngModel)]="sortOn"> </div> <div class="form-group"> <button type="button" (click)="getRepos()">Get Repos</button> </div> <div *ngIf="loading">loading...</div> <div *ngIf="errorMessage" class="alert alert-warning"> <strong>Warning!</strong> {{errorMessage}} </div> <div class='table-responsive'> <table class='table'> <thead> <tr> <th>ID</th> <th>Name</th> <th>HTML Url</th> <th>description</th> </tr> </thead> <tbody> <tr *ngFor="let repo of repos;"> <td>{{repo.id}}</td> <td>{{repo.name}}</td> <td>{{repo.html_url}}</td> <td>{{repo.description}}</td> </tr> </tbody> </table> </div> <pre>{{repos | json}}</pre> </div>