如何在拦截器中获取请求的查询参数 Angular

How to get query params of a request in interceptor Angular

我想从 get 请求中获取查询参数。拦截器代码是这样的,

export class FixtureInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
       return next.handle(req);
  }
}

我尝试使用这样的 get 方法获取参数,

req.params.get('category');

但它 returns 我总是空的。我的api电话是这样的,

getValue() {
     return this.http.get('http://139.49.10.175:3000/laundryItems?category=2&type=4');
}

我需要上面的类别和类型的值API调用

显然直接放在 url 中的参数没有出现在 req.params 中,这个应该可以工作:

  getValue() {
    return this.http.get('http://139.49.10.175:3000/laundryItems', {params: {category: '2', type: '4'}});
  }

好吧...我们又来了...HttpParams documentation 状态对象是不可变的。因此,为了构建集合,我们必须执行以下操作:

let params = new HttpParams().set("categoryName", "Cars");
if (search.length >= 2) {
  params = params.append("search", search);
}

添加到 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:

let search = request.params.get("search");

另请参阅the section about using HttpParams in this article