I would like to trigger HTTP request from an Angular component, but I do not know how to add URL arguments (query string) to it.
this.http.get(StaticSettings.BASE_URL).subscribe(
(response) => this.onGetForecastResult(response.json()),
(error) => this.onGetForecastError(error.json()),
() => this.onGetForecastComplete()
)
Now my StaticSettings.BASE_URL
is like a URL without query string like: http://atsomeplace.com/
but I want it to be like http://atsomeplace.com/?var1=val1&var2=val2
How to add var1
, and var2
to my HTTP request object as an object?
{
query: {
var1: val1,
var2: val2
}
}
and then just the HTTP module does the job to parse it into URL query string.
This question is related to
http
angular
typescript
Angular 6
You can pass in parameters needed for get call by using params:
this.httpClient.get<any>(url, { params: x });
where x = { property: "123" }.
As for the api function that logs "123":
router.get('/example', (req, res) => {
console.log(req.query.property);
})
import ...
declare var $:any;
...
getSomeEndPoint(params:any): Observable<any[]> {
var qStr = $.param(params); //<---YOUR GUY
return this._http.get(this._adUrl+"?"+qStr)
.map((response: Response) => <any[]> response.json())
.catch(this.handleError);
}
provided that you have installed jQuery, I do npm i jquery --save
and include in apps.scripts
in angular-cli.json
With Angular 5 and up, you DON'T have to use HttpParams. You can directly send your json object as shown below.
let data = {limit: "2"};
this.httpClient.get<any>(apiUrl, {params: data});
Please note that data values should be string, ie; { params: {limit: "2"}}
Use HttpParams, HttpClient from @angular/common/http
import { HttpParams, HttpClient } from '@angular/common/http';
...
constructor(private httpClient: HttpClient) { ... }
...
let params = new HttpParams();
params = params.append("page", 1);
....
this.httpClient.get<any>(apiUrl, {params: params});
Also, try stringifying your nested object using JSON.stringify()
.
My example
private options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})});
My method
getUserByName(name: string): Observable<MyObject[]> {
//set request params
let params: URLSearchParams = new URLSearchParams();
params.set("name", name);
//params.set("surname", surname); for more params
this.options.search = params;
let url = "http://localhost:8080/test/user/";
console.log("url: ", url);
return this.http.get(url, this.options)
.map((resp: Response) => resp.json() as MyObject[])
.catch(this.handleError);
}
private handleError(err) {
console.log(err);
return Observable.throw(err || 'Server error');
}
in my component
userList: User[] = [];
this.userService.getUserByName(this.userName).subscribe(users => {
this.userList = users;
});
By postman
http://localhost:8080/test/user/?name=Ethem
In latest Angular 7/8, you can use the simplest approach:-
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
getDetails(searchParams) {
const httpOptions = {
headers: { 'Content-Type': 'application/json' },
params: { ...searchParams}
};
return this.http.get(this.Url, httpOptions);
}
If you plan on sending more than one parameter.
private options = {
sort: '-id',
select: null,
limit: 1000,
skip: 0,
from: null,
to: null
};
constructor(private service: Service) { }
ngOnInit() {
this.service.getAllItems(this.options)
.subscribe((item: Item[]) => {
this.item = item;
});
}
private options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})});
constructor(private http: Http) { }
getAllItems(query: any) {
let params: URLSearchParams = new URLSearchParams();
for(let key in query){
params.set(key.toString(), query[key]);
}
this.options.search = params;
this.header = this.headers();
And continue with your http request just how @ethemsulan did.
router.get('/api/items', (req, res) => {
let q = {};
let skip = req.query.skip;
let limit = req.query.limit;
let sort = req.query.sort;
q.from = req.query.from;
q.to = req.query.to;
Items.find(q)
.skip(skip)
.limit(limit)
.sort(sort)
.exec((err, items) => {
if(err) {
return res.status(500).json({
title: "An error occurred",
error: err
});
}
res.status(200).json({
message: "Success",
obj: items
});
});
});
You can use HttpParams from @angular/common/http and pass a string with the query. For example:
import { HttpClient, HttpParams } from '@angular/common/http';
const query = 'key=value' // date=2020-03-06
const options = {
params: new HttpParams({
fromString: query
})
}
Now in your code
this.http.get(urlFull, options);
And this works for you :)
I hoppe help you
You can use Url Parameters from the official documentation.
Example: this.httpClient.get(this.API, { params: new HttpParams().set('noCover', noCover) })
HttpClient has been introduced along with HttpParams. Below an example of use :
import { HttpParams, HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) { }
let params = new HttpParams();
params = params.append('var1', val1);
params = params.append('var2', val2);
this.http.get(StaticSettings.BASE_URL, {params: params}).subscribe(...);
(Old answers)
requestOptions.search
has been deprecated. Use requestOptions.params
instead :
let requestOptions = new RequestOptions();
requestOptions.params = params;
You need to import URLSearchParams
as below
import { Http, RequestOptions, URLSearchParams } from '@angular/http';
And then build your parameters and make the http request as the following :
let params: URLSearchParams = new URLSearchParams();
params.set('var1', val1);
params.set('var2', val2);
let requestOptions = new RequestOptions();
requestOptions.search = params;
this.http.get(StaticSettings.BASE_URL, requestOptions)
.toPromise()
.then(response => response.json())
...
import { Http, Response } from '@angular/http';
constructor(private _http: Http, private router: Router) {
}
return this._http.get('http://url/login/' + email + '/' + password)
.map((res: Response) => {
return res.json();
}).catch(this._handleError);
Source: Stackoverflow.com