[译] 如何手动启动 Angular 程序

原文连接: How to manually bootstrap an Angular application

Angular 官方文档写到,为了启动 Angular 程序,必须在 main.ts 文件里写上以下代码:html

platformBrowserDynamic().bootstrapModule(AppModule);

这行代码 platformBrowserDynamic() 是为了构造一个 platform,Angular 官方文档对 platform 的定义是(译者注:为清晰理解,platform 定义不翻译):git

the entry point for Angular on a web page. Each page has exactly one platform, and services (such as reflection) which are common to every Angular application running on the page are bound in its scope.

同时,Angular 也有 运行的程序实例(running application instance)的概念,你可使用 ApplicationRef 标记(token)做为参数注入从而获取其实例。上文的 platform 定义也隐含了一个 platform 能够拥有多个 application 对象,而每个 application 对象是经过 bootstrapModule 构造出来的,构造方法就像上文 main.ts 文件中使用的那样。因此,上文的 main.ts 文件中代码,首先构造了一个 platform 对象和一个 application 对象。github

application 对象被正在构造时,Angular 会去检查模块 AppModulebootstrap 属性,该模块是用来启动程序的:web

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

bootstrap 属性一般包含用来启动程序的组件(译者注:即根组件),Angular 会在 DOM 中查询并匹配到该启动组件的选择器,而后实例化该启动组件。bootstrap

Angular 启动过程隐含了你想要哪个组件去启动程序,可是若是启动程序的组件是在运行时才被定义的该怎么办呢?当你得到该组件时,又该如何启动程序呢?事实上这是个很是简单的过程。api

NgDoBootstrap

假设咱们有 AB 两个组件,将编码决定运行时使用哪个组件来启动程序,首先让咱们定义这两个组件吧:数组

import { Component } from '@angular/core';

@Component({
  selector: 'a-comp',
  template: `<span>I am A component</span>`
})
export class AComponent {}

@Component({
  selector: 'b-comp',
  template: `<span>I am B component</span>`
})
export class BComponent {}

而后在 AppModule 中注册这两个组件:服务器

@NgModule({
  imports: [BrowserModule],
  declarations: [AComponent, BComponent],
  entryComponents: [AComponent, BComponent]
})
export class AppModule {}

注意,这里由于咱们得自定义启动程序,从而没有在 bootstrap 属性而是 entryComponents 属性中注册这两个组件,而且经过在 entryComponents 注册组件,Angular 编译器(译者注:Angular 提供了 @angular/compiler 包用来编译咱们写的 angular 代码,同时还提供了 @angular/compiler-cli CLI 工具)会为这两个组件建立工厂类(译者注:Angular Compiler 在编译每个组件时,会首先把该组件类转换为对应的组件工厂类,即 a.component.ts 被编译为 a.component.ngfactory.ts)。由于 Angular 会自动把在 bootstrap 属性中注册的组件自动加入入口组件列表,因此一般不须要把根组件注册到 entryComponents 属性中。(译者注:即在 bootstrap 属性中注册的组件不须要在 entryComponents 中重复注册)。app

因为咱们不知道 A 仍是 B 组件会被使用,因此无法在 index.html 中指定选择器,因此 index.html 看起来只能这么写(译者注:咱们不知道服务端返回的是 A 仍是 B 组件信息):ide

<body>
  <h1 id="status">
     Loading AppComponent content here ...
  </h1>
</body>

若是此时运行程序会有以下错误:

The module AppModule was bootstrapped, but it does not declare “@NgModule.bootstrap” components nor a “ngDoBootstrap” method. Please define one of these

错误信息告诉咱们, Angular 在向抱怨咱们没有指定具体使用哪个组件来启动程序,可是咱们的确不能提早知道(译者注:咱们不知道服务端什么时候返回什么)。等会儿咱们得手动在 AppModule 类中添加 ngDoBootstrap 方法来启动程序:

export class AppModule {
  ngDoBootstrap(app) {  }
}

Angular 会把 ApplicationRef 做为参数传给 ngDoBootstrap(译者注:参考 Angular 源码中这一行),等会准备启动程序时,使用 ApplicationRefbootstrap 方法初始化根组件。

让咱们写一个自定义方法 bootstrapRootComponent 来启动根组件:

// app - reference to the running application (ApplicationRef)
// name - name (selector) of the component to bootstrap
function bootstrapRootComponent(app, name) {
  // define the possible bootstrap components 
  // with their selectors (html host elements)
  // (译者注:定义从服务端可能返回的启动组件数组)
  const options = {
    'a-comp': AComponent,
    'b-comp': BComponent
  };
  // obtain reference to the DOM element that shows status
  // and change the status to `Loaded` 
  //(译者注:改变 id 为 #status 的内容)
  const statusElement = document.querySelector('#status');
  statusElement.textContent = 'Loaded';
  // create DOM element for the component being bootstrapped
  // and add it to the DOM
  // (译者注:建立一个 DOM 元素)
  const componentElement = document.createElement(name);
  document.body.appendChild(componentElement);
  // bootstrap the application with the selected component
  const component = options[name];
  app.bootstrap(component); // (译者注:使用 bootstrap() 方法启动组件)
}

传入该方法的参数是 ApplicationRef 和启动组件的名称,同时定义变量 options 来映射全部可能的启动组件,并以组件选择器做为 key,当咱们从服务器中获取所须要信息后,再根据该信息查询是哪个组件类。

先构建一个 fetch 方法来模拟 HTTP 请求,该请求会在 2 秒后返回 B 组件选择器即 b-comp 字符串:

function fetch(url) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('b-comp');
    }, 2000);
  });
}

如今咱们拥有 bootstrap 方法来启动组件,在 AppModule 模块的 ngDoBootstrap 方法中使用该启动方法吧:

export class AppModule {
  ngDoBootstrap(app) {
    fetch('url/to/fetch/component/name')
      .then((name)=>{ this.bootstrapRootComponent(app, name)});
  }
}

这里我作了个 stackblitz demo 来验证该解决方法。(译者注:译者把该做者 demo 中 angular 版本升级到最新版本 5.2.9,能够查看 angular-bootstrap-process,2 秒后会根据服务端返回信息自定义启动 application

在 AOT 中能工做么?

固然能够,你仅仅须要预编译全部组件,并使用组件的工厂类来启动程序:

import {AComponentNgFactory, BComponentNgFactory} from './components.ngfactory.ts';
@NgModule({
  imports: [BrowserModule],
  declarations: [AComponent, BComponent]
})
export class AppModule {
  ngDoBootstrap(app) {
    fetch('url/to/fetch/component/name')
      .then((name) => {this.bootstrapRootComponent(app, name);});
  }
  bootstrapRootComponent(app, name) {
    const options = {
      'a-comp': AComponentNgFactory,
      'b-comp': BComponentNgFactory
    };
    ...

记住咱们不须要在 entryComponents 属性中注册组件,由于咱们已经有了组件的工厂类了,不必再经过 Angular Compiler 去编译组件得到组件工厂类了。(译者注:components.ngfactory.ts 是由 Angular AOT Compiler 生成的,最新 Angular 版本 在 CLI 里隐藏了该信息,在内存里临时生成 xxx.factory.ts 文件,不像以前版本能够经过指令物理生成这中间临时文件,保存在硬盘里。)