假import { Injectable } from '@angular/core';
import {
HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';

import { Observable } from 'rxjs';

/* Pass untouched request through to the next request handler. /
@Injectable()
export class NoopInterceptor implements HttpInterceptor {

intercept(req: HttpRequest<any>, next: HttpHandler):

Observable<HttpEvent<any>> {return next.handle(req);

}
}

这个 NoopInterceptor 是由 Angular 的依赖注入 (DI) 系统管理的服务。 与其余服务一样,开发人员必须先提供拦截器类(Interceptor Class),而后利用能力应用它。因为拦截器是 HttpClient 服务的可选依赖项(`optional dependencies`),因而必须在提供 HttpClient 的同一注入器或注入器的父级中提供它们。 DI 创立 HttpClient 后提供的拦截器将被疏忽。如果应用程序在应用程序的根注入器中提供 HttpClient,作为在 AppModule 中导入 HttpClientModule 的副作用,那么也应该在 AppModule 中提供拦截器。从 `@angular/common/http` 导入 HTTP_INTERCEPTORS 注入令牌后,依照下列模式为 NoopInterceptor 提供 provider.

{ provide: HTTP_INTERCEPTORS, useClass: NoopInterceptor, multi: true },

留神下面代码的 `multi: true` 选项。 这个设置通知 Angular, `HTTP_INTERCEPTORS` 是一个用于注入`一组值`,而不是注入`单个值`的 `多提供者`的令牌。思考创立一个 `barrel index` 文件,将所有拦截器提供者的代码,收集到一个 httpInterceptorProviders 数组中。这个 barrel index 文件的文件名为 index.ts, 内容如下:

/ "Barrel" of Http Interceptors /
import { HTTP_INTERCEPTORS } from '@angular/common/http';

import { NoopInterceptor } from './noop-interceptor';

/* Http interceptor providers in outside-in order /
export const httpInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: NoopInterceptor, multi: true },
];

而后咱们在 App Module 里间接从 `index.ts` 里导入 httpInterceptorProviders 数组即可:

providers: [
httpInterceptorProviders
],

上面咱们看一看 Spartacus 的 SiteContextInterceptor 是如何被导入 NgModule 的。发现它被导入一个名为 `SiteContextOcc` 的 module 之中。![](https://img-blog.csdnimg.cn/img_convert/1629188952c9eafcd93a0a333068d504.png)在这个 module 里,咱们应用了 `useExisting` 而非 `useClass`:![](https://img-blog.csdnimg.cn/img_convert/3a9ddc174adcffd1be82bcd99f8c6881.png)useExisting 相当于 provider alias,即别名。

{provide: Class2, useExisting: Class2}

下面的代码并不会导致 Angular DI 框架被动为 Class2 创立实例。运行时如果构造函数申请 Class2 的实例,Angular DI 会为 key 为 Class2 的依赖,寻找另一个 `provider`,并从这个 Class2 提供者中取出注入实例。 开发人员能够把 `useExisting` 看成对另一个提供者或别名的援用。