Use the HttpParams
class with the params
request option to add URL query strings in your HttpRequest
.
The following example, the searchHeroes()
method queries for heroes whose names contain the search term.
Start by importing HttpParams
class.
import {HttpParams} from "@angular/common/http";
/* GET heroes whose name contains search term */ searchHeroes(term: string): Observable<Hero[]> { term = term.trim(); // Add safe, URL encoded search parameter if there is a search term const options = term ? { params: new HttpParams().set('name', term) } : {}; return this.http.get<Hero[]>(this.heroesUrl, options) .pipe( catchError(this.handleError<Hero[]>('searchHeroes', [])) ); }
If there is a search term, the code constructs an options object with an HTML URL-encoded search parameter. If the term is "cat", for example, the GET request URL would be api/heroes?name=cat
.
The HttpParams
object is immutable. If you need to update the options, save the returned value of the .set()
method.
You can also create HTTP parameters directly from a query string by using the fromString
variable:
const params = new HttpParams({fromString: 'name=foo'});
© 2010–2023 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/guide/http-configure-http-url-parameters