typescript 如何将参数传递给 HttpInterceptor?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46075602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass a param to HttpInterceptor?
提问by Amitabh
I am using Angular 4.3.1 and HttpClient. There is an HttpInterceptor to set some headers.
我正在使用 Angular 4.3.1 和 HttpClient。有一个 HttpInterceptor 来设置一些标头。
In some http get requests I need to set a different header. Is there anyway I can pass some param to this HttpInterceptor for that particular HttpRequest?
在某些 http get 请求中,我需要设置不同的标头。无论如何,我可以将一些参数传递给该特定 HttpRequest 的 HttpInterceptor 吗?
@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if(request.custom.param1) // how can i do this
request = request.clone({
setHeaders: {
'header1': 'xxxxxx'
}
});
else
request = request.clone({
setHeaders: {
'header2': 'yyyyyy'
}
});
return next.handle(request);
}
}
回答by Aleksey L.
Maybe there's a better way to handle this problem, but as a workaround you can create and pass custom HttpParams
to request and then check them in the interceptor. For example:
也许有更好的方法来处理这个问题,但作为一种解决方法,您可以创建并传递自定义HttpParams
到请求,然后在拦截器中检查它们。例如:
export class CustomHttpParams extends HttpParams {
constructor(public param1: boolean) {
super();
}
}
Using this class in http call:
在 http 调用中使用这个类:
this.http.get('https://example.com', {
params: new CustomHttpParams(true)
})
And now in interceptor:
现在在拦截器中:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (request.params instanceof CustomHttpParams && request.params.param1)
request = request.clone({
setHeaders: {
'header1': 'xxxxxx'
}
});
else
request = request.clone({
setHeaders: {
'header2': 'yyyyyy'
}
});
return next.handle(request);
}
回答by JWess
I wrote an interceptor for handling Http error responses. I wanted to allow specific Http calls to instruct the interceptor to ignore certain response status codes, while also retaining the ability to pass params to the Http call. Here is the solution I ended up with. (Thanks, Aleksey for the initial idea in your answer).
我写了一个拦截器来处理 Http 错误响应。我希望允许特定的 Http 调用指示拦截器忽略某些响应状态代码,同时还保留将参数传递给 Http 调用的能力。这是我最终得到的解决方案。(谢谢,Aleksey 在你的回答中给出了最初的想法)。
Extend HttpParams:
扩展HttpParams:
import { HttpParams } from '@angular/common/http';
import { HttpParamsOptions } from '@angular/common/http/src/params';
// Cause the HttpErrorInterceptor to ignore certain error response status codes like this:
//
// this.http.get<TypeHere>(`URL_HERE`, {
// params: new InterceptorHttpParams({ statusCodesToIgnore: [400, 401] }, {
// complete: 'false',
// offset: '0',
// limit: '50'
// })
// })
export class InterceptorHttpParams extends HttpParams {
constructor(
public interceptorConfig: { statusCodesToIgnore: number[] },
params?: { [param: string]: string | string[] }
) {
super({ fromObject: params } as HttpParamsOptions);
}
}
Interceptor:
拦截器:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
tap(
() => {},
(error: any) => {
if (error instanceof HttpErrorResponse) {
const regEx = /^[4-5][0-9][0-9]$/; // 4XX and 5XX status codes
if (regEx.test(error.status.toString())) {
const errorMessage = this.getErrorMessageFromStatus(error.status);
if (!this._shouldIgnoreError(req, error)) {
console.log(`ERROR INTERCEPTOR: ${error.status}`);
this.toastService.alert(errorMessage);
}
}
}
})
);
}
// Based on `request.params.interceptorConfig.statusCodesToIgnore`, we can see if we should ignore this error.
_shouldIgnoreError(request: HttpRequest<any>, errorResponse: HttpErrorResponse) {
if (request.params instanceof InterceptorHttpParams
&& Array.isArray(request.params.interceptorConfig.statusCodesToIgnore)
&& request.params.interceptorConfig.statusCodesToIgnore.includes(errorResponse.status)) {
return true;
}
return false;
}
回答by Rajnikant Baflipara
You can use setParam option of request.
您可以使用请求的 setParam 选项。
export class WebReqInterceptor implements HttpInterceptor {
stringifiedData: any;
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<any> {
if (window.sessionStorage.getItem('token')) {
this.stringifiedData=JSON.parse(window.sessionStorage.getItem('token'));
request = request.clone({
setParams:{
access_token:this.stringifiedData.access_token
}
});
return next.handle(request);
}
else{
return next.handle(request);
}
}
}
}