Пример для Http Interceptor на одном из моих проектов:
Где apiUrl - это место, где ваш URL API определен в файлах environment.ts.
@Injectable()
export class HttpRequestInterceptorService implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const url = environment.apiUrl;
req = req.clone({
url: url + req.url,
headers: new HttpHeaders({
'Cache-Control': 'no-cache',
'Pragma': 'no-cache',
'Expires': 'Sat, 01 Jan 2000 00:00:00 GMT'
})
});
return next.handle(req)
.pipe(catchError(error => {
if ((<HttpErrorResponse>error).status === 401) {
console.log(error);
}
return throwError(error);
}));
}
}
Модуль для регистрации:
@NgModule({
declarations: [],
imports: [
CommonModule,
HttpClientModule
],
providers: [
]
})
export class WebRequestInterceptorModule {
constructor(@Optional() @SkipSelf() parentModule: WebRequestInterceptorModule) {
if (parentModule) {
throw new Error('WebRequestInterceptorModule is already loaded. Import it in AppModule only');
}
}
static forRoot(): ModuleWithProviders {
return {
ngModule: WebRequestInterceptorModule,
providers: [
{provide: HTTP_INTERCEPTORS, useClass: HttpRequestInterceptorService, multi: true}
]
};
}
}
Тогда зарегистрируйте это в своем app.module.ts
WebRequestInterceptorModule.forRoot()