Angular框架解讀--依賴注入的引導(dǎo)過(guò)程
作為“為大型前端項(xiàng)目”而設(shè)計(jì)的前端框架,Angular 其實(shí)有許多值得參考和學(xué)習(xí)的設(shè)計(jì),本系列主要用于研究這些設(shè)計(jì)和功能的實(shí)現(xiàn)原理。本文主要圍繞 Angular 中的最大特點(diǎn)——依賴注入,介紹 Angular 依賴注入在體系在應(yīng)用引導(dǎo)過(guò)程中的的設(shè)計(jì)和實(shí)現(xiàn)。
多級(jí)依賴注入中,介紹了模塊注入器和元素注入器兩種層次結(jié)構(gòu)的注入器。那么,Angular 在引導(dǎo)過(guò)程中,又是如何初始化根模塊和入口組件的呢?
Angular 的引導(dǎo)過(guò)程
前面我們說(shuō)到,Angular 應(yīng)用在瀏覽器中引導(dǎo)時(shí),會(huì)創(chuàng)建瀏覽器平臺(tái),并引導(dǎo)根模塊:
- platformBrowserDynamic().bootstrapModule(AppModule);
引導(dǎo)根模塊
根模塊 AppModule
在 Angular 中,每個(gè)應(yīng)用有至少一個(gè) Angular 模塊,根模塊就是你用來(lái)引導(dǎo)此應(yīng)用的模塊,它通常命名為 AppModule。
當(dāng)你使用 Angular CLI 命令 ng new 生成一個(gè)應(yīng)用時(shí),其默認(rèn)的 AppModule 是這樣的:
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
- import { AppComponent } from './app.component';
- @NgModule({
- declarations: [
- AppComponent
- ],
- imports: [
- BrowserModule
- ],
- providers: [],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
引導(dǎo)根模塊的過(guò)程
我們來(lái)看看平臺(tái)層引導(dǎo)根模塊的過(guò)程中都做了些什么:
- @Injectable()
- export class PlatformRef {
- ...
- bootstrapModuleFactory<M>(moduleFactory: NgModuleFactory<M>, options?: BootstrapOptions):
- Promise<NgModuleRef<M>> {
- // 由于實(shí)例化模塊時(shí),會(huì)需要?jiǎng)?chuàng)建一些提供者,所以這里需要在實(shí)例化模塊之前創(chuàng)建 NgZone
- // 因此,這里創(chuàng)建了一個(gè)僅包含新 NgZone 的微型父注入器,并將其作為父?jìng)鬟f給 NgModuleFactory
- const ngZoneOption = options ? options.ngZone : undefined;
- const ngZoneEventCoalescing = (options && options.ngZoneEventCoalescing) || false;
- const ngZoneRunCoalescing = (options && options.ngZoneRunCoalescing) || false;
- const ngZone = getNgZone(ngZoneOption, {ngZoneEventCoalescing, ngZoneRunCoalescing});
- const providers: StaticProvider[] = [{provide: NgZone, useValue: ngZone}];
- // ApplicationRef 將在 Angular zone 之外創(chuàng)建
- return ngZone.run(() => {
- // 在 ngZone.run 中創(chuàng)建 ngZoneInjector,以便在 Angular zone 中創(chuàng)建所有實(shí)例化的服務(wù)
- const ngZoneInjector = Injector.create(
- {providers: providers, parent: this.injector, name: moduleFactory.moduleType.name});
- const moduleRef = <InternalNgModuleRef<M>>moduleFactory.create(ngZoneInjector);
- const exceptionHandler: ErrorHandler|null = moduleRef.injector.get(ErrorHandler, null);
- if (!exceptionHandler) {
- throw new Error('No ErrorHandler. Is platform module (BrowserModule) included?');
- }
- ...
- return _callAndReportToErrorHandler(exceptionHandler, ngZone!, () => {
- const initStatus: ApplicationInitStatus = moduleRef.injector.get(ApplicationInitStatus);
- initStatus.runInitializers();
- return initStatus.donePromise.then(() => {
- ...
- // 引導(dǎo)模塊
- this._moduleDoBootstrap(moduleRef);
- return moduleRef;
- });
- });
- });
- }
- bootstrapModule<M>(
- moduleType: Type<M>,
- compilerOptions: (CompilerOptions&BootstrapOptions)|
- Array<CompilerOptions&BootstrapOptions> = []): Promise<NgModuleRef<M>> {
- const options = optionsReducer({}, compilerOptions);
- // 編譯并創(chuàng)建 @NgModule 的實(shí)例
- return compileNgModuleFactory(this.injector, options, moduleType)
- .then(moduleFactory => this.bootstrapModuleFactory(moduleFactory, options));
- }
- private _moduleDoBootstrap(moduleRef: InternalNgModuleRef<any>): void {
- const appRef = moduleRef.injector.get(ApplicationRef) as ApplicationRef;
- // 引導(dǎo)應(yīng)用程序
- if (moduleRef._bootstrapComponents.length > 0) {
- // 在應(yīng)用程序的根級(jí)別引導(dǎo)新組件
- moduleRef._bootstrapComponents.forEach(f => appRef.bootstrap(f));
- } else if (moduleRef.instance.ngDoBootstrap) {
- moduleRef.instance.ngDoBootstrap(appRef);
- } else {
- ...
- }
- this._modules.push(moduleRef);
- }
- }
根模塊引導(dǎo)時(shí),除了編譯并創(chuàng)建 AppModule 的實(shí)例,還會(huì)創(chuàng)建 NgZone,關(guān)于 NgZone 的請(qǐng)參考。在編譯和創(chuàng)建 AppModule 的過(guò)程中,便會(huì)創(chuàng)建 ApplicationRef
,即 Angular 應(yīng)用程序。
引導(dǎo) Angular 應(yīng)用程序
前面在引導(dǎo)根模塊過(guò)程中,創(chuàng)建了 Angular 應(yīng)用程序之后,便會(huì)在應(yīng)用程序的根級(jí)別引導(dǎo)新組件:
- // 在應(yīng)用程序的根級(jí)別引導(dǎo)新組件
- moduleRef._bootstrapComponents.forEach(f => appRef.bootstrap(f));
我們來(lái)看看這個(gè)過(guò)程會(huì)發(fā)生什么。
應(yīng)用程序 ApplicationRef
一個(gè) Angular 應(yīng)用程序,提供了以下的能力:
- @Injectable()
- export class ApplicationRef {
- // 獲取已注冊(cè)到該應(yīng)用程序的組件類型的列表
- public readonly componentTypes: Type<any>[] = [];
- // 獲取已注冊(cè)到該應(yīng)用程序的組件的列表
- public readonly components: ComponentRef<any>[] = [];
- // 返回一個(gè) Observable,指示應(yīng)用程序何時(shí)穩(wěn)定或不穩(wěn)定
- // 如果在應(yīng)用程序引導(dǎo)時(shí),引導(dǎo)任何種類的周期性異步任務(wù),則該應(yīng)用程序?qū)⒂肋h(yuǎn)不會(huì)穩(wěn)定(例如輪詢過(guò)程)
- public readonly isStable!: Observable<boolean>;
- constructor(
- private _zone: NgZone, private _injector: Injector, private _exceptionHandler: ErrorHandler,
- private _componentFactoryResolver: ComponentFactoryResolver,
- private _initStatus: ApplicationInitStatus) {
- // 創(chuàng)建時(shí),主要進(jìn)行兩件事:
- // 1. 宏任務(wù)結(jié)束后,檢測(cè)視圖是否需要更新。
- // 2. 在 Angular Zone 之外創(chuàng)建對(duì) onStable 的預(yù)訂,以便在 Angular Zone 之外運(yùn)行回調(diào)。
- }
- // 在應(yīng)用程序的根級(jí)別引導(dǎo)新組件
- bootstrap<C>(componentOrFactory: ComponentFactory<C>|Type<C>, rootSelectorOrNode?: string|any):
- ComponentRef<C> {}
- // 調(diào)用此方法以顯式處理更改檢測(cè)及其副作用
- tick(): void {}
- // 關(guān)聯(lián)視圖,以便對(duì)其進(jìn)行臟檢查,視圖銷毀后將自動(dòng)分離
- attachView(viewRef: ViewRef): void {}
- // 再次從臟檢查中分離視圖
- detachView(viewRef: ViewRef): void {}
- }
那么,我們來(lái)看看 bootstrap()
過(guò)程中,Angular 都做了些什么。
在應(yīng)用程序的根級(jí)別引導(dǎo)根組件
將新的根組件引導(dǎo)到應(yīng)用程序中時(shí),Angular 將指定的應(yīng)用程序組件安裝到由 componentType
的選擇器標(biāo)識(shí)的 DOM 元素上,并引導(dǎo)自動(dòng)更改檢測(cè)以完成組件的初始化。
- @Injectable()
- export class ApplicationRef {
- bootstrap<C>(componentOrFactory: ComponentFactory<C>|Type<C>, rootSelectorOrNode?: string|any):
- ComponentRef<C> {
- ...
- // 如果未與其他模塊綁定,則創(chuàng)建與當(dāng)前模塊關(guān)聯(lián)的工廠
- const ngModule =
- isBoundToModule(componentFactory) ? undefined : this._injector.get(NgModuleRef);
- const selectorOrNode = rootSelectorOrNode || componentFactory.selector;
- // 創(chuàng)建組件
- const compRef = componentFactory.create(Injector.NULL, [], selectorOrNode, ngModule);
- const nativeElement = compRef.location.nativeElement;
- // 創(chuàng)建可測(cè)試服務(wù)掛鉤
- const testability = compRef.injector.get(Testability, null);
- const testabilityRegistry = testability && compRef.injector.get(TestabilityRegistry);
- if (testability && testabilityRegistry) {
- testabilityRegistry.registerApplication(nativeElement, testability);
- }
- // 組件銷毀時(shí),銷毀關(guān)聯(lián)視圖以及相關(guān)的服務(wù)
- compRef.onDestroy(() => {
- this.detachView(compRef.hostView);
- remove(this.components, compRef);
- if (testabilityRegistry) {
- testabilityRegistry.unregisterApplication(nativeElement);
- }
- });
- // 加載組件,包括關(guān)聯(lián)視圖、監(jiān)聽(tīng)變更等
- this._loadComponent(compRef);
- ...
- return compRef;
- }
- }
在創(chuàng)建根組件的過(guò)程中,會(huì)關(guān)聯(lián) DOM 元素視圖、添加對(duì)狀態(tài)變更的檢測(cè)機(jī)制。
根組件是一個(gè)入口組件,Angular CLI 創(chuàng)建的默認(rèn)應(yīng)用只有一個(gè)組件 AppComponent
,Angular 會(huì)在引導(dǎo)過(guò)程中把它加載到 DOM 中。
在根組件的創(chuàng)建過(guò)程中,通常會(huì)根據(jù)根組件中引用到的其他組件,觸發(fā)一系列組件的創(chuàng)建并形成組件樹(shù)。大多數(shù)應(yīng)用只有一個(gè)組件樹(shù),并且只從一個(gè)根組件開(kāi)始引導(dǎo)。
創(chuàng)建組件過(guò)程
Angular 中創(chuàng)建組件的過(guò)程如下:
- 當(dāng) Angular 創(chuàng)建組件類的新實(shí)例時(shí),它會(huì)通過(guò)查看該組件類的構(gòu)造函數(shù),來(lái)決定該組件依賴哪些服務(wù)或其它依賴項(xiàng)。
- 當(dāng) Angular 發(fā)現(xiàn)某個(gè)組件依賴某個(gè)服務(wù)時(shí),它會(huì)首先檢查是否該注入器中已經(jīng)有了那個(gè)服務(wù)的任何現(xiàn)有實(shí)例。如果所請(qǐng)求的服務(wù)尚不存在,注入器就會(huì)使用以前注冊(cè)的服務(wù)提供者來(lái)制作一個(gè),并把它加入注入器中,然后把該服務(wù)返回給 Angular。
- 當(dāng)所有請(qǐng)求的服務(wù)已解析并返回時(shí),Angular 可以用這些服務(wù)實(shí)例為參數(shù),調(diào)用該組件的構(gòu)造函數(shù)。
Angular 會(huì)在執(zhí)行應(yīng)用時(shí)創(chuàng)建注入器,第一個(gè)注入器是根注入器,創(chuàng)建于引導(dǎo)過(guò)程中。借助注入器繼承機(jī)制,可以把全應(yīng)用級(jí)的服務(wù)注入到這些組件中。
到這里,Angular 分別完成了根模塊、根組件和組件樹(shù)的引導(dǎo)過(guò)程,通過(guò)編譯器則可以將組件和視圖渲染到頁(yè)面上。
總結(jié)
在應(yīng)用程序的引導(dǎo)過(guò)程中,Angular 采取了以下步驟來(lái)加載我們的第一個(gè)視圖:
- index.html
- Main.ts
本文我們重點(diǎn)從根模塊的引導(dǎo)過(guò)程開(kāi)始,介紹了引導(dǎo) Angular 應(yīng)用程序、引導(dǎo)根組件、組件的創(chuàng)建等過(guò)程。至于組件樹(shù)的創(chuàng)建和渲染,則可以參考 編譯器 相關(guān)的內(nèi)容。