SAP 实用篇SAP

SAP Spartacus HTTP Interceptor 的

2022-10-10  本文已影响0人  _扫地僧_
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 之中。

在这个 module 里,我们使用了 useExisting 而非 useClass

useExisting 相当于 provider alias,即别名。

{provide: Class2, useExisting: Class2}

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

上一篇下一篇

猜你喜欢

热点阅读