This article mainly introduces how to manually start the angularjs program. Here is a detailed explanation of how to manually start the angularjs program. Now let us take a look at how to manually start the angularjs program
Angular official documentation states that in order to start the Angular program, the following code must be written in the main.ts
file:
platformBrowserDynamic().bootstrapModule(AppModule);
This line of codeplatformBrowserDynamic()
is to construct a platform
. Angular’s official documentation defines platform
as (Translator’s Note: For clear understanding, platform
Definition not translated):
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.
At the same time, Angular also has the concept of running application instance, which you can use the ApplicationRef
token to inject as a parameter to obtain its examples. The platform
definition above also implies that a platform
can have multiple application
objects, and each application
object is passed bootstrapModule
is constructed, and the construction method is the same as that used in the main.ts
file above. Therefore, the code in the main.ts
file above first constructs a platform
object and an application
object.
When the application
object is being constructed, Angular will check the bootstrap
attribute of the module AppModule
, which is used to start the program :
@NgModule({ imports: [BrowserModule], declarations: [AppComponent], bootstrap: [AppComponent] }) export class AppModule {}
bootstrap
The attribute usually contains the component used to start the program (Translator's Note: Root component). Angular will query and match the selector of the startup component in the DOM. Then instantiate the startup component. (If you want to see more, go to PHP Chinese website AngularJS Development Manual to learn)
Angular startup process implies which component you want to start the program, but if the component of the startup program What should I do if it is defined at runtime? When you get the component, how do you start the program? It's actually a very simple process.
Assume we have two components A
and B
. We will code to determine which component to use to start the program at runtime. First let us define These two components:
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 {}
Then register these two components in AppModule
:
@NgModule({ imports: [BrowserModule], declarations: [AComponent, BComponent], entryComponents: [AComponent, BComponent] }) export class AppModule {}
Note that because we have to customize the startup program, there is no The bootstrap
property registers these two components in the entryComponents
property, and by registering the component in the entryComponents
, the Angular compiler (Translator's Note: Angular provides @angular/compiler
package is used to compile the angular code we wrote, and also provides @angular/compiler-cli
CLI tool) Factory classes will be created for these two components (Translator's Note: When Angular Compiler compiles each component, it will first convert the component class into the corresponding component factory class, that is, a.component.ts is compiled into a.component. ngfactory.ts). Because Angular will automatically add components registered in the bootstrap
attribute to the entry component list, there is usually no need to register the root component in the entryComponents
attribute. (Translator's Note: That is, components registered in the bootstrap
attribute do not need to be repeatedly registered in entryComponents
).
Since we don’t know whether the A
or B
component will be used, we cannot specify the selector in index.html
, so index.html
It seems that it can only be written like this (Translator's Note: We don't know whether the server returns A
or B
component information):
<body> <h1 id="status"> Loading AppComponent content here ... </h1> </body>
If At this time, the following error will occur when running the program:
The module AppModule was bootstrapped, but it does not declare “@NgModule.bootstrap” components nor a “ngDoBootstrap” method. Please define one of these
The error message tells us that Angular is complaining that we did not specify which component to use to start the program, but we really can't know in advance (Translator's Note: We don't know when the server will return anything). Later we have to manually add the ngDoBootstrap
method to the AppModule
class to start the program:
export class AppModule { ngDoBootstrap(app) { } }
Angular will pass ApplicationRef
as a parameter ngDoBootstrap
(Translator's Note: Refer to this line in the Angular source code), when you are ready to start the program, use the bootstrap
method of ApplicationRef
to initialize the root component.
Let us write a custom method bootstrapRootComponent
to start the root component:
// 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
)
当然可以,你仅仅需要预编译所有组件,并使用组件的工厂类来启动程序:
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 文件,不像之前版本可以通过指令物理生成这中间临时文件,保存在硬盘里。)
好了,本篇文章到这就结束了(想看更多就到PHP中文网AngularJS使用手册中学习),有问题的可以在下方留言提问。
The above is the detailed content of How to manually start an Angular program? Detailed explanation of manually starting the angularjs program. For more information, please follow other related articles on the PHP Chinese website!