【问题标题】:Why "bootstrap" key in @NgModule is an array?为什么@NgModule 中的“bootstrap”键是一个数组?
【发布时间】:2017-08-03 11:16:03
【问题描述】:

据我所知,一个应用程序只能有一个入口点。如下面给出的代码 sn-p 所示,我们在引导键中传递了一个数组,该数组决定了应用程序的入口点。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent, MyComboboxComponent, 
                    CollapsibleDirective, CustomCurrencyPipe],
  imports: [BrowserModule],
  providers: [UserService, LessonsService],
  bootstrap: [AppComponent]

})
export class AppModule {

}

P.S:我正在学习 Angular 2,这个问题可能听起来很傻 :)

【问题讨论】:

标签: angular


【解决方案1】:

您可以传递任意数量的引导组件。您最终会得到几个独立的组件树:

bootstrap: [AComponent, BComponent]

        RootModuleInjector
                |
                |
       ApplicationRef.views
       /                   \
      /                     \
   AComponent              BComponent

另见What are the implications of bootstrapping multiple components

当运行变更检测时,Angular 将分别为每棵树运行变更检测:

class ApplicationRef {
   tick(): void {
    ...
    try {
      this._runningTick = true;
      // here this._views.length equals to 2
      this._views.forEach((view) => view.detectChanges());

如果您愿意,您甚至可以手动将新的根组件添加到 ApplicationRef:

const componentRef = componentFactoryResolver.resolveComponentFactory(SomeComponent)
applicationRef.attachView(componentRef.hostView);

        RootModuleInjector
                |
                |
       ApplicationRef.views
       /        |           \
      /         |            \
AComponent  SomeComponent   BComponent

如果您需要在根组件之间共享一些数据,您可以在根模块上定义一个提供程序,该提供程序将用于创建一个 RootModuleInjector:

@NgModule({
    providers: [ServiceSharedBetweenRootComponents]
}
export class AppModule {}

然后你就可以将它注入到每个根组件中:

export class AComponent {
    constructor(service: ServiceSharedBetweenRootComponents)

【讨论】:

  • 两个或多个independent trees with a single injector可以通信吗?怎么样?
  • 只需在根模块上定义一个服务并注入到每个组件中
  • 如图AComponent 和BComponent 所示。哪一个是根模块?您的意思是在提供程序中注入@NGModule 级别的服务吗?
  • @VikasBansal "如果我在根组件中注入任何服务" 不是根组件,而是根模块。根模块中的提供程序(您引导组件的同一模块)在应用程序之间共享
  • 非常感谢您的宝贵时间和精彩的解释。了解这些深刻的东西是件好事。 :)
【解决方案2】:

一个应用程序只能有一个入口点

没有。您可以将多个组件实例化为应用程序的入口点。

示例:https://stackoverflow.com/a/36566919/5706293

这是我们如何在根组件之间进行通信的示例

【讨论】:

    猜你喜欢
    • 2017-02-06
    • 1970-01-01
    • 2017-03-16
    • 2015-01-24
    • 2015-01-22
    • 2014-01-28
    • 2019-03-02
    • 2019-06-21
    • 1970-01-01
    相关资源
    最近更新 更多