简体   繁体   中英

Angular URLSearchParams Vs HttpParams

Previously am using with

import { Http, Response, Headers, URLSearchParams  } from "@angular/http";

And for the API Call

getprojectscount(city, param){
let urlSearchParams = new URLSearchParams();
  urlSearchParams.set('limit', param.limit );
  urlSearchParams.set('limitrows', param.limitrows );
  urlSearchParams.set('locality', param.locality );

return this.http
    .get(this.myapiurl + city + "?", { search: urlSearchParams })
    .pipe(map(response => response.json().Counts));

}

In this URLSEARCHPARAMS Method it is working perfectly. -> Because When we are passing params. When its needed that time only it will pass to the urlSearchParams.

Currently Am using with

import {  HttpErrorResponse, HttpParams } from '@angular/common/http';

AND Comes to HttpParams. When am using this HTTPPARAMS, Every time every params are passing through the api, If it is null also.

And for the API call

getprojectcount(city,param){
let params = new HttpParams();
params = params.append('limit', param.limit);
 params = params.append('limitrows', param.limitrows);
 params = params.append('locality', param.locality);
 return this.httpClient.get(this.myapiurl + city + "?", {params: params} ).pipe(retry(3), catchError(this.handleError));
}

Any solution for this. Because from this httpparams. If params is null also it is passing.

you can achieve it with helper function

    getprojectcount(param){
       return this.http.get(url, {params: toHttpParams(param)});
     }
   
     export function toHttpParams(obj: Object): HttpParams {
       return Object.getOwnPropertyNames(obj)
         .filter((key) => obj[key] !== undefined && obj[key] !== null )
         .reduce((p, key) => p.set(key, obj[key]), new HttpParams());
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM