Angular 如何根据一个 class 的定义和数据,动态创建一个该类的实例

JerryWang_汪子熙 -
Angular 如何根据一个 class 的定义和数据,动态创建一个该类的实例

可以从 SAP 电商云 Spartacus UI 的实现中找到一个例子。

    return this.resolveModuleFactory(moduleFunc).pipe(
      map(([moduleFactory]) => moduleFactory.create(parentInjector)),
      concatMap((moduleRef) => this.runModuleInitializersForModule(moduleRef)),
      tap((moduleRef) =>
        this.events.dispatch(
          createFrom(ModuleInitializedEvent, {
            feature,
            moduleRef,
          })
        )
      )
    );
  }

下图这段代码,createFrom 方法的输入参数 ModuleInitializedEvent,是我们在另一个 TypeScript 文件里定义的一个 class,而 feature 和 moduleRef,是实例数据:

createFrom 的实现:

/**
 * Creates an instance of the given class and fills its properties with the given data.
 *
 * @param type reference to the class
 * @param data object with properties to be copied to the class
 */
export function createFrom<T>(type: Type<T>, data: T): T {
  console.log('Jerry dynamically created new instance for type: ', type , ' with data: ' , data);
  return Object.assign(new type(), data);
}

这里传入的 class 定义,和传入的实例数据,必须严格匹配:

例如 ModuleInitializedEvent 的字段 feature 和 moduleRef,在我们传入 createFrom 函数的实例数据里是一一对应的。

更多Jerry的原创文章,尽在:"汪子熙":

特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

Tags 标签

javascripthtml5css3typescriptangular

扩展阅读

加个好友,技术交流

1628738909466805.jpg