[英]How to get query params of a request in interceptor Angular
I want to get the query params from an get request.我想从获取请求中获取查询参数。 Interceptor code is this way,
拦截器代码是这样的,
export class FixtureInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req);
}
}
i tried to get the params using get method like this ,我尝试使用这样的 get 方法获取参数,
req.params.get('category');
but it returns me null always.但它总是返回 null。 My api call is this way ,
我的api调用是这样的,
getValue() {
return this.http.get('http://139.49.10.175:3000/laundryItems?category=2&type=4');
}
i need value of category and type from above API call我需要来自上述 API 调用的类别和类型的值
Apparently params directly putted in url doesn't appear in req.params
, this one should work:显然,直接放在 url 中的 params 没有出现在
req.params
,这个应该可以工作:
getValue() {
return this.http.get('http://139.49.10.175:3000/laundryItems', {params: {category: '2', type: '4'}});
}
Well... here we are again... HttpParams documentation states object is immutable.好吧……我们又来了…… HttpParams 文档说明对象是不可变的。 Therefore, in order to build the collection we must do something like:
因此,为了构建集合,我们必须执行以下操作:
let params = new HttpParams().set("categoryName", "Cars");
if (search.length >= 2) {
params = params.append("search", search);
}
Adding to http.get
must take this form:添加到
http.get
必须采用以下形式:
this.http.get<Product[]>(`${this.baseUrl}products`, { params }).subscribe(result => {
this.products = result;
}, error => {
console.error(error)
});
IMPORTANT: The wrapping of
params
in brace-brackets is required - especially if you want to retrieve the params, like by some interceptor - for example:重要提示:需要将
params
包装在大括号中 - 特别是如果您想检索参数,例如通过某些拦截器 - 例如:
let search = request.params.get("search");
Also, refer to the section about using HttpParams in this article .另请参阅本文中有关使用 HttpParams 的部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.