Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 HttpClient Path Variable

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?

like image 658
Jose A. Matarán Avatar asked Mar 10 '18 16:03

Jose A. Matarán


2 Answers

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.

like image 197
ambussh Avatar answered Nov 02 '22 12:11

ambussh


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); }
like image 2
GreyBeardedGeek Avatar answered Nov 02 '22 13:11

GreyBeardedGeek