关于sap:SAP-电商云-Spartacus-UI-里的-InjectionToken-应用场景

7次阅读

共计 1781 个字符,预计需要花费 5 分钟才能阅读完成。

看个具体的例子:

InjectionToken 构造函数,须要传一个类型参数进去。

这个 ActionReducerMap 的定义很考究:

export declare type ActionReducerMap<T, V extends Action = Action> = {[p in keyof T]: ActionReducer<T[p], V>;
};

应用这个类型时,须要传入两个类型参数 T 和 V,其中 V 的默认值就是 Action.

ActionReducerMap<State> 形容了一个对象,其字段名必须是 State 字段的其中之一,该字段的类型为 ActionReducer<T[p],V>

咱们看,State 类型的字段名称正好为 ROUTING_FEATURE 即 ‘router’:

即下图红色高亮区域:

那么 router 的类型呢?
必须为 ActionReducer<State[p],V>

State[p] = State[‘router’] 即咱们自定义的 RouterState

也就是说,ActionReducer 当初第一个类型参数即 T,变成了 RouterState.

ActionReducer<RouterState> =
{
函数
}

括号里是一个函数,输出参数有两个:

  • state:类型为 RouterState
  • action:参数为 Action

返回参数类型为 RouterState

正好和咱们利用代码里定义的统一:

应用 injection Token 的场合

每当你要注入的类型无奈确定(没有运行时示意模式)时,例如在注入接口、可调用类型、数组或 参数化类型 时,都应应用 InjectionToken.

Token 构造函数里的类型参数 T:

InjectionToken 在 T 上的参数化版本,T 是 Injector 返回的对象的类型。这提供了更高级别的类型安全性。

上面是 Injection Token 创立的几种办法。

办法 1

const BASE_URL = new InjectionToken<string>('BaseUrl');
const injector =
    Injector.create({providers: [{provide: BASE_URL, useValue: 'http://localhost'}]});
const url = injector.get(BASE_URL);
// here `url` is inferred to be `string` because `BASE_URL` is `InjectionToken<string>`.
expect(url).toBe('http://localhost');

办法 2:创立能够摇树优化的 injection token

class MyService {constructor(readonly myDep: MyDep) {}}

const MY_SERVICE_TOKEN = new InjectionToken<MyService>('Manually constructed MyService', {
  providedIn: 'root',
  factory: () => new MyService(inject(MyDep)),
});

const instance = injector.get(MY_SERVICE_TOKEN);
expect(instance instanceof MyService).toBeTruthy();
expect(instance.myDep instanceof MyDep).toBeTruthy();

看一个 Spartacus 例子:

routing.module.ts 里提供了 reducerToken 和 reducerToken providers 的实现:采取 factory 实现:

reducerProvider 里保护了 reducerToken 和如何 provide 其的 factory,reducerProvider 什么时候被援用呢?

答案是配置在了 RoutingModule 里:

最初我通过下列代码拿到 token 对应的运行时实例:

constructor(_injector: Injector){const jerry = _injector.get(reducerToken);
    console.log('Jerry token:', jerry);
  }

就是一个 reducer 函数:

这个函数定义如下:

更多 Jerry 的原创文章,尽在:” 汪子熙 ”:

正文完
 0