头图

An example can be found in the implementation of SAP e-commerce cloud 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,
          })
        )
      )
    );
  }

In the code below, the input parameter ModuleInitializedEvent of the createFrom method is a class we defined in another TypeScript file, and feature and moduleRef are instance data:

Implementation of 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);
}

The class definition passed in here must match the incoming instance data strictly:

For example, the feature and moduleRef fields of ModuleInitializedEvent have a one-to-one correspondence in the instance data we pass in the createFrom function.

More original articles by Jerry, all in: "Wang Zixi":


注销
1k 声望1.6k 粉丝

invalid