SAP Spartacus HTTP Interceptor 的 provisioning 逻辑

JerryWang_汪子熙 -
SAP Spartacus HTTP Interceptor 的 provisioning 逻辑

假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` 看成对另一个提供者或别名的引用。
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

Tags 标签

前端javascripttypescripthtmlhtml5

扩展阅读

加个好友,技术交流

1628738909466805.jpg