const resolvedProviderMap = mergeResolvedReflectiveProviders(resolved, new Map()); export function mergeResolvedReflectiveProviders( providers: ResolvedReflectiveProvider[], normalizedProvidersMap: Map<number, ResolvedReflectiveProvider>): Map<number, ResolvedReflectiveProvider> { for (let i = 0; i < providers.length; i++) { const provider = providers[i]; // 从normalizedProvidersMap对象中获取key.id对应的ResolvedReflectiveProvider对象 const existing = normalizedProvidersMap.get(provider.key.id); if (existing) { // 如果当前的provider不是multi provider,则抛出异常 if (provider.multiProvider !== existing.multiProvider) { throw mixingMultiProvidersWithRegularProvidersError(existing, provider); } // 如果当前的provider是multi provider,则把当前provider的resolvedFactories // 列表中的每一项添加到已存在的provider对象的resolvedFactories列表中。 if (provider.multiProvider) { for (let j = 0; j < provider.resolvedFactories.length; j++) { existing.resolvedFactories.push(provider.resolvedFactories[j]); } } else { // 如果当前的provider不是multi provider,则覆盖已存在的provider normalizedProvidersMap.set(provider.key.id, provider); } } else { let resolvedProvider: ResolvedReflectiveProvider; // 如果当前的provider是multi provider,则创建一个新的ResolvedReflectiveProvider对象 if (provider.multiProvider) { resolvedProvider = new ResolvedReflectiveProvider_( provider.key, provider.resolvedFactories.slice(), provider.multiProvider); } else { resolvedProvider = provider; } // 在normalizedProvidersMap中保存已解析的ResolvedReflectiveProvider对象 normalizedProvidersMap.set(provider.key.id, resolvedProvider); } } return normalizedProvidersMap; }
步骤四 —— 生成ResolvedReflectiveProvider[]
// resolvedProviderMap的values,创建ResolvedReflectiveProvider[] Array.from(resolvedProviderMap.values()); /** * 基于一个类似数组或可迭代对象创建一个新的数组实例 * * arrayLike:转换成真实数组的类数组对象或可遍历对象。 * mapFn(可选):如果指定了该参数,则最后生成的数组会经过该函数的加工处理后再返回。 * thisArg(可选):执行mapFn函数时this的值。 */ Array.from(arrayLike[, mapFn[, thisArg]])
fromResolvedProviders()
该方法用于基于已解析的 providers 创建注入器。
static fromResolvedProviders(providers: ResolvedReflectiveProvider[], parent?: Injector): ReflectiveInjector { return new ReflectiveInjector_(providers, parent); }
fromResolvedProviders() 使用示例
@Injectable() class Engine {} @Injectable() class Car { constructor(public engine:Engine) {} } var providers = ReflectiveInjector.resolve([Car, Engine]); var injector = ReflectiveInjector.fromResolvedProviders(providers); expect(injector.get(Car) instanceof Car).toBe(true);
了解完 fromResolvedProviders() 方法的使用方式,接下来我们来重点分析一下 ReflectiveInjector_ 类。
ReflectiveInjector_ 类
ReflectiveInjector_ 类的属性