Angular 如何根据一个 class 的定义和数据,动态创建一个该类的实例
生活随笔
收集整理的這篇文章主要介紹了
Angular 如何根据一个 class 的定义和数据,动态创建一个该类的实例
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
可以從 SAP 電商云 Spartacus UI 的實現(xiàn)中找到一個例子。
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 方法的輸入?yún)?shù) ModuleInitializedEvent,是我們在另一個 TypeScript 文件里定義的一個 class,而 feature 和 moduleRef,是實例數(shù)據(jù):
createFrom 的實現(xiàn):
/*** 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 定義,和傳入的實例數(shù)據(jù),必須嚴(yán)格匹配:
例如 ModuleInitializedEvent 的字段 feature 和 moduleRef,在我們傳入 createFrom 函數(shù)的實例數(shù)據(jù)里是一一對應(yīng)的。
更多Jerry的原創(chuàng)文章,盡在:“汪子熙”:
總結(jié)
以上是生活随笔為你收集整理的Angular 如何根据一个 class 的定义和数据,动态创建一个该类的实例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 真我 Buds Air5 Pro 无线耳
- 下一篇: SAP 电商云 Spartacus UI