簡體   English   中英

從Typescript / Angular2中的類字符串創建實例

[英]Create instance from class string in Typescript/Angular2

我一直在研究使用Javascript中的字符串創建類,直到遇到以下情況:

var instance = new window[classString]();

但是,這似乎在Typescript中不起作用,因為缺少類型信息。

細節:

interface SomeInterface{
  structuredData: any;
}

class A implements SomeInterface {

}

我將JSON序列化的類信息存儲在數據庫中。 假設我有一個模型類A ,該類的屬性在前端被序列化為JSON字符串,並與代表該數據的類名一起發送到數據庫,即數據庫包含一個class_type列,該列包含該類的名稱。 在這種情況下,它將是字符串“ A”。 現在,我想將這些數據返回到我的應用程序中,並根據該數據動態構造一個實例。

如果我們看一下我在上面找到的Javascript實例化代碼,我很想做這樣的事情:

let instance = new window['A']();
instance.structuredData = foo;

由於這些類包含遵循某個接口的通用參數,因此我可以將序列化的數據分配給那些新實例化的實例。

我正在使用Angular2 / Webpack,並且非常感謝有關如何執行此操作的任何提示。

當使用上面提到的代碼時,出現以下編譯器錯誤:

無法對類型缺少調用或構造簽名的表達式使用'new'。

如果我嘗試通過使用規避嚴格類型檢查

declare var window;

我收到以下錯誤:

window ['classString']不是構造函數

由於Angular2熟練地抽象了Webpack的內容,因此我不知道確切如何詳細加載和處理模塊。 但是,我的猜測(如評論中所述)是該類在窗口/全局空間中不可用,因此我想出了一個可能正確的解決方案(嘗試過並可以使用,但不確定是否正確)做這種事情的方式):

// first I require the module that is named in snake case with a .ts
// suffix based on the string that is stored in the database
// so if the stored string is SomeThing, we require the file
// called 'some_thing.ts'. Note: using lodash to generate that string
const dynModule = require('./' + _.snakeCase(classTypeString));

// next, we get the constructor by the class name from that module
// which is exactly the string that we stored in the db
const klass = dynModule[classTypeString];

// now we have the constructor function of the class and can
// instantiate a new class from that
let instance: SomeInterface = new klass();

instance.structuredData = foo;

您可以自己將這些類放在window對象中,即使您位於其他類中也可以:

(window as any).example = class {}; // replace with you class
// and then later in code....
const classNameStr = 'example';
const init = new window[classNameStr]();

如果您不喜歡在window對象內部編寫代碼,可以將它們存儲在代碼中某個對象/字典中。 或簡單地使用Eval(盡管使用它不是一個好習慣):

eval(`new ${className}()`);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM