I'm developing an Angular Client for a REST API.
My api exposes URL like:
https://server.com/users/detail/3
Where 3 is a parameter.
I try to generate a path variable using Angular Client but I have not been able. I try
getUser(username: string) {
const options = {
params: new HttpParams().set('username', username)
};
return this.http.get<User>('detail/{username}', options); }
But the result isn't correct. Can someone help me?
EDIT
After I try the solutions, it doesn't still work. If
getUser(username: string) {
const options = {
params: new HttpParams().set('username', username)
};
const resource = 'detail/' + username;
return this.http.get<any>(resource); }
This solution seems me too poor, Has Angular HttpClient any solution for this?
Because use http.get your parameter should be inserted in the URL:
getUser(username: string): void {
let url = `https://server.com/users/detail/${username}`;
this.http.get< User >(url)
//if api returns any data
.subscribe((returnObject: User) => {
//returned data
//remember that this segment will be returned asynchronously
//for example: callback(returnObject);
}, (error: HttpErrorResponse) => {
//if error
//for example: errorCallback(error)
})
}
If you want set HttpParams you should use this.http.post - of course if the server supports the post instead of get.
Your second attempt is close, but you need to use a dollar sign and backticks instead of single-quotes to get the string interpolation to work:
return this.http.get<User>(`detail/${username}`, options); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With