美文网首页
Angular 如何根据一个 class 的定义和数据,动态创建

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

作者: _扫地僧_ | 来源:发表于2021-12-10 09:09 被阅读0次

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


    相关文章

      网友评论

          本文标题:Angular 如何根据一个 class 的定义和数据,动态创建

          本文链接:https://www.haomeiwen.com/subject/jjnuzltx.html