详解Angular 4.x Injector(2)

export interface ResolvedReflectiveProvider { // 唯一的对象用来从ReflectiveInjector中获取对象 key: ReflectiveKey; // 工厂函数用于创建key相关的依赖对象 resolvedFactories: ResolvedReflectiveFactory[]; // 标识当前的provider是否为multi-provider multiProvider: boolean; }

ResolvedReflectiveFactory 类

export class ResolvedReflectiveFactory { constructor( public factory: Function, public dependencies: ReflectiveDependency[]) {} }

ReflectiveDependency 类

export class ReflectiveDependency { constructor( public key: ReflectiveKey, public optional: boolean, public visibility: Self|SkipSelf|null) {} static fromKey(key: ReflectiveKey): ReflectiveDependency { return new ReflectiveDependency(key, false, null); } }

ReflectiveKey 类

ReflectiveKey 对象中包含两个属性:系统范围内唯一的id 和 token。系统范围内唯一的id,允许注入器以更高效的方式存储已创建的对象。另外我们不能手动的创建 ReflectiveKey,当 ReflectiveInjector 对象解析 providers 的时候会自动创建 ReflectiveKey 对象。

export class ReflectiveKey { constructor(public token: Object, public id: number) { if (!token) { throw new Error('Token must be defined!'); } } // 返回序列化的token get displayName(): string { return stringify(this.token); } // 获取token对应的ReflectiveKey static get(token: Object): ReflectiveKey { return _globalKeyRegistry.get(resolveForwardRef(token)); } // 获取系统中已注册ReflectiveKey的个数 static get numberOfKeys(): number { return _globalKeyRegistry.numberOfKeys; } } const _globalKeyRegistry = new KeyRegistry(); // 创建Key仓库 export class KeyRegistry { private _allKeys = new Map<Object, ReflectiveKey>(); /** * 若token是ReflectiveKey类的实例,则直接返回。若_allKeys对象中包含token属性 * 则返回token对应的ReflectiveKey对象。否则创建一个新的ReflectiveKey对象,并 * 保存到_allKeys对象中 */ get(token: Object): ReflectiveKey { if (token instanceof ReflectiveKey) return token; if (this._allKeys.has(token)) { return this._allKeys.get(token) !; } const newKey = new ReflectiveKey(token, ReflectiveKey.numberOfKeys); this._allKeys.set(token, newKey); return newKey; } // 获取已保存ReflectiveKey的个数 get numberOfKeys(): number { return this._allKeys.size; } }

分析完 resolve() 方法的输入参数和返回类型,我们来看一下该方法内部的具体实现:

export function resolveReflectiveProviders(providers: Provider[]) : ResolvedReflectiveProvider[] { const normalized = _normalizeProviders(providers, []); // 步骤一 const resolved = normalized.map(resolveReflectiveProvider); // 步骤二 const resolvedProviderMap = mergeResolvedReflectiveProviders(resolved, new Map()); // 步骤三 return Array.from(resolvedProviderMap.values()); // 步骤四 }

步骤一 —— 规范化Provider

const normalized = _normalizeProviders(providers, []); // 规范化Providers function _normalizeProviders(providers: Provider[], res: Provider[]): Provider[] { providers.forEach(b => { // providers: [Type] => providers: [{provide: Type, useClass: Type }] if (b instanceof Type) { res.push({provide: b, useClass: b}); } else if (b && typeof b == 'object' && (b as any).provide !== undefined) { res.push(b as NormalizedProvider); } else if (b instanceof Array) { // 若b是数组,则递归调用_normalizeProviders()方法 _normalizeProviders(b, res); } else { throw invalidProviderError(b); } }); return res; } interface NormalizedProvider extends TypeProvider, ValueProvider, ClassProvider, ExistingProvider, FactoryProvider {}

步骤二 —— 转化NormalizedProvider为ResolvedReflectiveProvider

const resolved = normalized.map(resolveReflectiveProvider); // 解析NormalizedProvider为ResolvedReflectiveProvider function resolveReflectiveProvider(provider: NormalizedProvider): ResolvedReflectiveProvider { return new ResolvedReflectiveProvider_( ReflectiveKey.get(provider.provide), [resolveReflectiveFactory(provider)], provider.multi || false); } // 用于创建已解析的Provider实例 export class ResolvedReflectiveProvider_ implements ResolvedReflectiveProvider { constructor( public key: ReflectiveKey, public resolvedFactories: ResolvedReflectiveFactory[], public multiProvider: boolean) {} get resolvedFactory(): ResolvedReflectiveFactory { return this.resolvedFactories[0]; } } // 解析NormalizedProvider对象,创建ResolvedReflectiveFactory对象 function resolveReflectiveFactory(provider: NormalizedProvider): ResolvedReflectiveFactory { let factoryFn: Function; let resolvedDeps: ReflectiveDependency[]; if (provider.useClass) { // { provide: ApiService, useClass: ApiService } const useClass = resolveForwardRef(provider.useClass); factoryFn = reflector.factory(useClass); resolvedDeps = _dependenciesFor(useClass); } else if (provider.useExisting) { // { provide: 'ApiServiceAlias', useExisting: ApiService } factoryFn = (aliasInstance: any) => aliasInstance; resolvedDeps = [ReflectiveDependency.fromKey(ReflectiveKey.get(provider.useExisting))]; } else if (provider.useFactory) { // { provide: APP_INITIALIZER, useFactory: configFactory, deps: [AppConfig], // multi: true } factoryFn = provider.useFactory; resolvedDeps = constructDependencies(provider.useFactory, provider.deps); } else { // { provide: 'API_URL', useValue: 'http://my.api.com/v1' } factoryFn = () => provider.useValue; // const _EMPTY_LIST: any[] = []; resolvedDeps = _EMPTY_LIST; } return new ResolvedReflectiveFactory(factoryFn, resolvedDeps); }

步骤三 —— 合并已解析的Provider

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wypydw.html