Angular应用页面里appId的生成逻辑和位置

109 阅读1分钟

DomRendererFactory2类的构造函数里,看到三个输入参数。我们感兴趣的是,appId这个三位随机字符,是如何生成的。

前面这个classRef是DomRendererFactory2的构造函数。后面是调用该构造函数传入的输入参数,我们要关注的appId也是这三个输入参数之一。

输入参数通过17396行…injectArgs依赖注入的方式生成。
…injectArgs的输入参数:

真正的参数实例化,发生在这个函数ɵɵinject里:

所有injectionToken的实例化,都发生在上图两个方法里。

准备生成AppId了:

typeof fn是Object:

检查record, 发现appId通过provider.useFactory创建:

provider.useFactory里就能看到生成appId的工厂函数了:

这就是我要找的随机字符生成函数:_appIdRandomProviderFactory()

AppID的生成,本身没有任何dependency:

直接生成三位随机字符:

/**
 * @fileoverview added by tsickle
 * Generated from: packages/core/src/application_tokens.ts
 * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
 */
/**
 * A DI Token representing a unique string id assigned to the application by Angular and used
 * primarily for prefixing application attributes and CSS styles when
 * {\@link ViewEncapsulation#Emulated ViewEncapsulation.Emulated} is being used.
 *
 * If you need to avoid randomly generated value to be used as an application id, you can provide
 * a custom value via a DI provider <!-- TODO: provider --> configuring the root {\@link Injector}
 * using this token.
 * \@publicApi
 * @type {?}
 */
const APP_ID = new InjectionToken('AppId');
/**
 * @return {?}
 */
function _appIdRandomProviderFactory() {
    return `${_randomChar()}${_randomChar()}${_randomChar()}`;
}
/**
 * Providers that will generate a random APP_ID_TOKEN.
 * \@publicApi
 * @type {?}
 */
const APP_ID_RANDOM_PROVIDER = {
    provide: APP_ID,
    useFactory: _appIdRandomProviderFactory,
    deps: (/** @type {?} */ ([])),
};
/**
 * @return {?}
 */
function _randomChar() {
    return String.fromCharCode(97 + Math.floor(Math.random() * 25));
}

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