能够从 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的原创文章,尽在:"汪子熙":