如何使用远程js文件中Typescript中的方法动态扩展class?

How to dynamically extend class with method in Typescript from remote js file?

我有包含 class 个组件的 TypeScript 代码。我想以某种方式使用远程 js 文件来扩展这个 classes 远程。所以我想当我的应用程序开始远程获取 js 文件并使用代码扩展所需 class。 如何扩展 class 我知道了。例如:

Import { UsersBlocksMyOrders } from "../pages/users/blocks/myorders";

declare module "../pages/users/blocks/myorders" {
    interface UsersBlocksMyOrders {
        logit(): void;
    }
}

UsersBlocksMyOrders.prototype.logit = function () { console.log(this); }

组件文件中的代码是:

import { APP_CONFIG } from "../../../app/app.config";

@Component({
  selector: 'menu-blocks-menupage',
  templateUrl: APP_CONFIG.appDomain + '/mobilesiteapp/template/?path=pages/menu/blocks/menupage'
})

export class MenuBlocksMenuPage{

  constructor(){
    this.logit();
  }
}

我的问题是我使用Webpack编译代码。 Webpack 创建函数名称不同的最终文件。这就是我无法直接访问 class 的原因。

这种情况怎么办?

  1. 创建服务以获取文件并扩展 class。您需要在 class 中有变量,它将在有键的地方存储对象。键是要扩展的 classes 的名称。以及导入的值 classes。在 init 函数中,我们使用原型方法进行循环扩展。

import { Http } from "@angular/http";
import { MenuBlocksMenuPage } from "../pages/menu/blocks/menupage";


export class ExtendService {
  allModules = {
    ...
    MenuBlocksMenuPage : MenuBlocksMenuPage,
    ...
  };

  constructor(public http: Http){ }

  init()
  {
    //Load json map to extend class
    this.http.get(APP_CONFIG.appDomain + '/modules/mobilesiteapp/view/js/extend.json').toPromise()
      .then((res) => {
        let json = res.json();

        //Loop each class to extend
        Object.keys(json).forEach((cl) => {
          //Add new functions and methods
          Object.keys(json[cl]).forEach((func) => {
            this.allModules[cl].prototype[func] = eval(json[cl][func]);
          });
        });

      }).catch((e) => {
        console.error(e);
      });
  }
}

  1. 请求 json 具有要评估的函数的文件。

{
    "MenuBlocksMenuPage": {
        "logit": "(function (){console.log(this);})"
    }
}