`Angular Platform` 创建相关
2020-09-07 本文已影响0人
niccky
Angular Platform
:
createPlatformFactory
createPlatform
createPlatformFactory
工厂函数 parentPlatformFactory
调用结束后 (=null
), 开始组合所有 providers
,然后创建 Root Injector
, 最后调用 createPlatform(...)
创建出 PlatformRef
实例.
export function createPlatformFactory(
parentPlatformFactory: ((extraProviders?: StaticProvider[]) => PlatformRef)|null, name: string,
providers: StaticProvider[] = []): (extraProviders?: StaticProvider[]) => PlatformRef {
const desc = `Platform: ${name}`;
const marker = new InjectionToken(desc);
return (extraProviders: StaticProvider[] = []) => {
let platform = getPlatform();
if (!platform || platform.injector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
if (parentPlatformFactory) {
parentPlatformFactory(
providers.concat(extraProviders).concat({provide: marker, useValue: true}));
} else {
const injectedProviders: StaticProvider[] =
providers.concat(extraProviders).concat({provide: marker, useValue: true}, {
provide: INJECTOR_SCOPE,
useValue: 'platform'
});
createPlatform(Injector.create({providers: injectedProviders, name: desc}));
}
}
return assertPlatform(marker);
};
}
createPlatform
通过 Root Injector
创建和取回 PlatformRef
, 而这个 PlatformRef
是在之前工厂里面的 providers
注册的,这里呢,不管那么多用就完了,哈哈哈。
漏了点东西, PLATFORM_INITIALIZER
, 这货的 multi
为 true
, 所以 injector.get(PLATFORM_INITIALIZER, null)
如果值不是 null
那就只能是个数组了。
如果 PLATFORM_INITIALIZER
取回来是个数组,那就逐个遍历调用那些通过 PLATFORM_INITIALIZER
定义的工厂函数,可以看做是平台初始化,当一切都搞定后,就返回 _platform
平台对象。
export function createPlatform(injector: Injector): PlatformRef {
if (_platform && !_platform.destroyed &&
!_platform.injector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
throw new Error(
'There can be only one platform. Destroy the previous one to create a new one.');
}
publishDefaultGlobalUtils();
_platform = injector.get(PlatformRef);
const inits = injector.get(PLATFORM_INITIALIZER, null);
if (inits) inits.forEach((init: any) => init());
return _platform;
}