Angular, createComponent() throws "ERROR TypeError: Cannot add property"

Angular, createComponent() throws "ERROR TypeError: Cannot add property"

我正在动态创建组件,我正在通过 ngrx 操作传递组件的 class,最终有:

loadComponent(componentType: Type<any>): void {
  const viewContainerRef = this.contentHost.viewContainerRef;
  viewContainerRef.clear();
  const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentType);
  const componentRef = viewContainerRef.createComponent(componentFactory);
  componentRef.instance.type = componentType;
}    

调用此方法后,我得到:

core.js:5980 ERROR TypeError: Cannot add property __NG_ELEMENT_ID__, object is not extensible
    at bloomAdd (core.js:3048)
    at diPublicInInjector (core.js:3190)
    at createRootComponentView (core.js:12159)
    at ComponentFactory.create (core.js:24822)
    at ViewContainerRef.createComponent (core.js:22896) <--- this is the createComponent()
    at WorkspaceSingleComponent.loadComponent (workspace-single.component.ts:45)  <---- this is my class
    at SafeSubscriber._next (workspace-single.component.ts:32)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)
    at SafeSubscriber.next (Subscriber.js:122)
    at Subscriber._next (Subscriber.js:72)

显然,当此组件 class 通过 ngrx 操作的序列化时,它会被冻结,我们无法使用它来构造新实例。

我们可以使用以下解决方法使其正常工作,直到找到更好的方法。在 app.module.ts 中,向您的 StoreModule 的初始化程序添加:

StoreModule.forRoot(reducers, {
      metaReducers,
      runtimeChecks: {
        strictActionImmutability: false,
        strictActionSerializability: false,
        strictActionTypeUniqueness: isDevMode(),
        strictActionWithinNgZone: isDevMode(),
        strictStateImmutability: isDevMode(),
        strictStateSerializability: false,
      }
    }),

感谢 Simon Hayden 提供此解决方法。资料来源:https://gitter.im/ngrx/platform?at=5f3cbaa33dac53434017de6a