Angular 依赖注入机制根据providers定义生成注入实例的框架代码
程序员文章站
2022-05-29 21:38:29
...
/**
* Converts a `SingleProvider` into a factory function.
*
* @param {?} provider provider to convert to factory
* @param {?=} ngModuleType
* @param {?=} providers
* @return {?}
*/
function providerToFactory(provider, ngModuleType, providers) {
/** @type {?} */
let factory = undefined;
if (isTypeProvider(provider)) {
/** @type {?} */
const unwrappedProvider = resolveForwardRef(provider);
return getFactoryDef(unwrappedProvider) || injectableDefOrInjectorDefFactory(unwrappedProvider);
}
else {
if (isValueProvider(provider)) {
factory = (/**
* @return {?}
*/
() => resolveForwardRef(provider.useValue));
}
else if (isFactoryProvider(provider)) {
factory = (/**
* @return {?}
*/
() => provider.useFactory(...injectArgs(provider.deps || [])));
}
else if (isExistingProvider(provider)) {
factory = (/**
* @return {?}
*/
() => ɵɵinject(resolveForwardRef(provider.useExisting)));
}
else {
/** @type {?} */
const classRef = resolveForwardRef(provider &&
(((/** @type {?} */ (provider))).useClass || provider.provide));
if (!classRef) {
throwInvalidProviderError(ngModuleType, providers, provider);
}
if (hasDeps(provider)) {
factory = (/**
* @return {?}
*/
() => new (classRef)(...injectArgs(provider.deps)));
}
else {
return getFactoryDef(classRef) || injectableDefOrInjectorDefFactory(classRef);
}
}
}
return factory;
}
UseValue和UseExisting可以在此处打断点调试:
而useClass的分支在下图,由此可见,useClass就是简单的new操作:
factory其实就是构造函数,只是由于Chrome开发者工具的限制,无法正确显示出来:
这里可见,useExisting如果没有实例,还是会调用构造函数new一个新的出来。
更多Jerry的原创文章,尽在:“汪子熙”: