通过数组在 Angular 6 中引导多个模块

Ang*_*uha 4 javascript frontend typescript angular angular6

是否可以声明一个数组并使用它来引导 module.ts 中的多个组件。我正在尝试这样的事情

    export var initialComponents = [];
    initialComponents.push(AppComponent);
    if(condition) {
      initialComponents.push(IchFooterComponent);
    }
Run Code Online (Sandbox Code Playgroud)

进而

bootstrap: initialComponents
Run Code Online (Sandbox Code Playgroud)

这给了我以下错误

错误:模块 oa 被引导,但它没有声明“@NgModule.bootstrap”组件,也没有声明“ngDoBootstrap”方法。请定义其中之一。

Sir*_*ter 7

您可以通过实现ngDoBootstrapas 的方法来自定义引导AppModule。您可以在entryComponents属性中列出需要引导的组件@NgModule

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

     constructor() {}

 ngDoBootstrap(app: ApplicationRef) {
     if (Math.random() > 0.5) {
         appRef.bootstrap(AComponent, '#app');
     } else {
         appRef.bootstrap(BComponent, '#app');
     }
 }
Run Code Online (Sandbox Code Playgroud)

如果你需要一个服务,你可以通过依赖注入来访问它们(把它作为构造函数参数放在 AppModule 中)。但是不知道在组件或者服务上相比DI有没有什么限制。以下是ApplicationRef及其引导方法的文档。