【问题标题】:Bootstrapping multiple module in Angular 6 via array通过数组在Angular 6中引导多个模块
【发布时间】:2018-12-17 23:03:22
【问题描述】:

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

    export var initialComponents = [];
    initialComponents.push(AppComponent);
    if(condition) {
      initialComponents.push(IchFooterComponent);
    }

然后

bootstrap: initialComponents

这给了我以下错误

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

【问题讨论】:

  • 你声明了@ngModule 吗? @NgModule({ declarations: initialComponents | Array<Type<any> | any[], bootstrap: Array<Type<any> | any[] })
  • 是的,我声明了 ng 模块

标签: javascript angular typescript frontend angular6


【解决方案1】:

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

@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');
     }
 }

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

【讨论】:

  • 拯救了我的一天!引导程序:[条件? ComponentOne : ComponentTwo] 在开发模式下工作,但 ng build --prod 崩溃:“AppModule 的 NgModule.bootstrap 中位置 0 的值不是参考:[object Object”。删除“bootstrap:”并通过 ngDoBootstrap 实现后构建和工作正常。
  • 不幸的是,装饰器(如@NgModule)内容(如bootstrap)非常脆弱,需要“非常静态”,特别是对于构建案例,当使用大量角度优化时)
【解决方案2】:

再试一次(下面是示例代码):

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; // <-- NgModel lives here

import { AppComponent } from './app.component';
import { HeroesComponent } from './heroes/heroes.component';

var initialComponents: any[] = []; 

initialComponents.push(AppComponent);
if (true) {
  initialComponents.push(HeroesComponent);
}

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

再试一次:

https://stackblitz.com/edit/angular-vimqb1?file=src/app/app.module.ts

【讨论】:

  • 我需要在 bootstrap 中声明多个组件,其中的几个应该根据条件出现。您的示例首先加载应用程序组件,然后从应用程序内部加载英雄组件,这不是我的用例。
  • 尝试将所有内容置于其应该工作的条件或外部条件中。那是一个数组类型的声明。根据我的理解,无论它应该如何工作。
猜你喜欢
  • 2017-01-27
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多