[英]HTTP_INTERCEPTOR for specific routes in Angular 4+
我已經創建了HTTP_INTERCEPTOR,我需要它在某些特定的路由上工作,而在其他一些路由上卻沒有。
一開始它是在主應用程序模塊文件中,然后我從那里刪除了它,並將其添加到某些模塊中,但是它仍然可以在所有路徑上使用,然后我將其添加到component.ts中,但根本不起作用。
{
provide: HTTP_INTERCEPTORS,
useClass: AuthExpiredInterceptor,
multi: true,
deps: [Injector]
},
僅為某些路由和/或模塊指定攔截器是不可能的。
但是,您可以添加一個http標頭值,該值將跳過對該請求應用攔截器。 例如:
import { HttpHeaders } from '@angular/common/http';
export const InterceptorSkip = 'X-Skip-Interceptor';
export const InterceptorSkipHeader = new HttpHeaders({
'X-Skip-Interceptor': ''
});
然后在我的錯誤處理程序Interceptor中,如果應用了標頭,則不要捕獲錯誤並進行處理,而應將其冒泡到我的服務和組件中。
@Injectable()
export class ErrorHandlerInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>,next: HttpHandler
): Observable<HttpEvent<any>> {
if (request.headers && request.headers.has(InterceptorSkip)) {
const headers = request.headers.delete(InterceptorSkip);
return next.handle(request.clone({ headers }));
}
return next.handle(request).pipe(catchError(this.processError));
}
...
}
那么只要您有一個HTTP請求,就想將其忽略即可,將InterceptorSkipHeader
添加到該請求中
this.http.get<ResponseModel>('api/url', { headers : InterceptorSkipHeader });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.