URL Parameters And Query Parameters In Angular HttpClient

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

The query above returns the results ordered by description and only returns the second page. After the question mark, the string sort=description&page=2 is referred to as a URL parameter or Query strings/Query Parameters. As a divider, the question mark is employed. The GET params are another name for URL parameters.

HttpParams()

The auxiliary class HttpParams is used to add URL parameters. HttpParams is one of the arguments supplied to the HttpClient.get method.

You must first import HttpParams as indicated below in order to use it.

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

Create a new body for the provided parameter name with a new value. If a parameter already exists, it will be replaced otherwise, it will be added.

params = new HttpParams()
    .set('page', '2')
    .set('page', '3')
    .set('sort', 'name');
 
console.log(params.toString()); //Returns page=3&sort=name

HTTPParams is immutable

The HttpParams object can't be changed. Every time you call a set method on the Params object, a new instance of the Params is created and returned.

As an example,

The code below does not function.

let params = new HttpParams();
 
params.set('page', PageNo);
params.set('sort', SortOn);

Each call to the set method produces a new instance from the existing one and returns it, rather than adding the options to the existing HttpParams object.

To get around this, use the following code.

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

page=2&page=3&sort=name is the URL structure.

You can also use the add method in the same way that you would the Set method.

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

The fromString shortcut is another way to pass the value.

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 can also add the arguments to the URL directly, bypassing the HttpParams, as demonstrated below.

//You an also do it this way.
return this.httpClient.get<repos[]>(this.baseURL + 'users/' + userName + '/repos?'+'page='+PageNo+'&sort='+SortOn);

Angular Httpparams Example

In app.module, Import the httpClientModule from the @angular/common/http package.

Add the following code under the app.module.ts file.

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

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule
  ],
  providers: [GitHubService],
  bootstrap: [AppComponent]
})

Passing the URL Parameters

Open the github.service.ts file in a text editor.

HttpClient and HttpParams are imported from @angular/common/http. RxJs' Observable module is also required.

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>

Conclusion

In this article, We learned how to pass Get Parameters or Request Parameters. When we use the httpClient.get method to invoke the HTTP get Request, we can receive parameters or request parameters.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post