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

时间:2019-05-15 05:41:08

标签: angular interceptor query-parameters angular-http-interceptors

我想从get请求中获取查询参数。拦截器代码就是这种方式,

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

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

req.params.get('category');

但是它总是返回null。我的api调用是这种方式,

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

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

2 个答案:

答案 0 :(得分:0)

显然,直接放在url中的参数没有出现在req.params中,该参数应该起作用:

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

答案 1 :(得分:0)

好吧...我们又来了... 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)
}); 

重要提示:params必须用大括号括起来,特别是如果您想像使用某些拦截器那样检索参数时,例如:

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

另外,请参考the section about using HttpParams中的this article