Angular9 配置 URL 参数
使用 HttpParams 类和 params 选项在你的 HttpRequest 中添加 URL 查询字符串。
下面的例子中,searchHeroes() 方法用于查询名字中包含搜索词的英雄。
首先导入 HttpParams 类。
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', []))
);
}
如果有搜索词,代码会用进行过 URL 编码的搜索参数来构造一个 options 对象。例如,如果搜索词是 "cat",那么 GET 请求的 URL 就是 api/heroes?name=cat。
HttpParams 是不可变对象。如果需要更新选项,请保留 .set() 方法的返回值。
你也可以使用 fromString 变量从查询字符串中直接创建 HTTP 参数:
const params = new HttpParams({fromString: 'name=foo'});