SAP 电商云 Spartacus UI 里的 InjectionToken 应用场景
看個(gè)具體的例子:
InjectionToken 構(gòu)造函數(shù),需要傳一個(gè)類型參數(shù)進(jìn)去。
這個(gè) ActionReducerMap 的定義很講究:
export declare type ActionReducerMap<T, V extends Action = Action> = {[p in keyof T]: ActionReducer<T[p], V>; };使用這個(gè)類型時(shí),需要傳入兩個(gè)類型參數(shù) T 和 V,其中 V 的默認(rèn)值就是 Action.
ActionReducerMap 描述了一個(gè)對(duì)象,其字段名必須是 State 字段的其中之一,該字段的類型為 ActionReducer<T[p],V>
我們看,State 類型的字段名稱正好為 ROUTING_FEATURE 即 ‘router’:
即下圖紅色高亮區(qū)域:
那么 router 的類型呢?
必須為 ActionReducer<State[p],V>
State[p] = State[‘router’] 即我們自定義的 RouterState
也就是說,ActionReducer 現(xiàn)在第一個(gè)類型參數(shù)即 T,變成了 RouterState.
ActionReducer =
{
函數(shù)
}
括號(hào)里是一個(gè)函數(shù),輸入?yún)?shù)有兩個(gè):
- state:類型為 RouterState
- action:參數(shù)為 Action
返回參數(shù)類型為 RouterState
正好和我們應(yīng)用代碼里定義的一致:
使用 injection Token 的場(chǎng)合
每當(dāng)你要注入的類型無法確定(沒有運(yùn)行時(shí)表示形式)時(shí),例如在注入接口、可調(diào)用類型、數(shù)組或參數(shù)化類型時(shí),都應(yīng)使用 InjectionToken.
Token 構(gòu)造函數(shù)里的類型參數(shù) T:
InjectionToken 在 T 上的參數(shù)化版本,T 是 Injector 返回的對(duì)象的類型。這提供了更高級(jí)別的類型安全性。
下面是 Injection Token 創(chuàng)建的幾種方法。
方法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:創(chuàng)建可以搖樹優(yōu)化的 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();看一個(gè) Spartacus 例子:
routing.module.ts 里提供了 reducerToken 和 reducerToken providers 的實(shí)現(xiàn):采取 factory 實(shí)現(xiàn):
reducerProvider 里維護(hù)了 reducerToken 和如何 provide 其的 factory,reducerProvider 什么時(shí)候被引用呢?
答案是配置在了 RoutingModule 里:
最后我通過下列代碼拿到 token 對(duì)應(yīng)的運(yùn)行時(shí)實(shí)例:
constructor(_injector: Injector){const jerry = _injector.get(reducerToken);console.log('Jerry token: ', jerry);}就是一個(gè) reducer 函數(shù):
這個(gè)函數(shù)定義如下:
更多Jerry的原創(chuàng)文章,盡在:“汪子熙”:
總結(jié)
以上是生活随笔為你收集整理的SAP 电商云 Spartacus UI 里的 InjectionToken 应用场景的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 抖音火山版省流模式怎么设置
- 下一篇: 得了夫人又得兵!男子32万买到二手泡水奔