Reputation: 2280
I have this kind of code, where I'm requesting an API with an empty string for the query param:
getArticles(params?: HttpParams): Observable<any> {
return this.http.get(this._articlesUrl, {
params: new HttpParams()
.set('page', this.page.toString())
.set('per_page', this.limit.toString())
.set('query', this.query.toString())
});
}
After calling the getArticles function, I'm getting this king of url: 127.0.0.1:8000/api/articles?page=1&per_page=6&query=
The question is: Does there any clean way where the query
param will not appear in the url, if it's an empty string ?
Upvotes: 0
Views: 3056
Reputation: 2280
I just created kind of function to iterate my params and remove undifined and null. All we need is to import the file in which is our function is difined and then we pass thereafter the necessary parameters as an argument.
import {HttpParams} from '@angular/common/http';
export function createHttpParams(params: {}): HttpParams {
let httpParams: HttpParams = new HttpParams();
Object.keys(params).forEach(param => {
if (params[param]) {
if (params[param] instanceof Array) {
params[param].forEach(value => {
httpParams = httpParams.append(param, value);
});
} else {
httpParams = httpParams.append(param, params[param]);
}
}
});
return httpParams;
}
If we made a request like this:
this.http.get('/api/articles', createHttpParams({
'page': this.page,
'per_page': this.limit,
'query': this.query, //null or undifined
'suppliers[]': this.suppliersIds //[1,4]
})
);
Our final url will looke like this ../api/articles?page=1&per_page=5&suppliers[]=1&suppliers[]=4
Upvotes: 1
Reputation: 109
I'm curious if the blank value affects your query results. Regardless, if it really bothers you could you could write a function to only add query params if they're present. e.g.
private setQueryParams(): HttpParams {
const params = new HttpParams();
if (this.page) {
params.set('page', this.page.toString());
}
...etc
return params;
}
Upvotes: 0