I noticed that there are two ways of adding query parameters to HTTP requests in angular. I was not sure which approach to follow in my application.
1.Append the query parameters as strings to the URL as below :
let value1='...', value2='...';
const url = `${this.baseUrl}?param1=${value1}¶m2=${value2}`;
this.http.get(url).subscribe(...);
2.Use HttpParams object to add the query parameters and use it while making the API call as below :
let baseUrl='...', value1='...', value2='...';
let params = new HttpParams()
.set('param1', value1);
.set('param2', value2);
this.http.get(baseUrl, {params: params}).subscribe(...);
I was wondering which is the better approach among the two and why? Or which scenarios are best suited for each of these methods?
HttpParams comes with a set of handy functions if you have some complex logic before sending params (append for example).
It also does the "?" and "&" logic by itself which means you don't need to worry about param1 if it was not set, example :
const params = new HttpParams();
if (param1) {
params.set('param1', param1);
}
if (param2) {
// Here with a string concatenation you would need to do "if first param then ? else &"
params.set('param2', param2);
}
Yet those two syntaxes are valid and the choice might be opiniated ?
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.