Angular中的新函数构造函数如何在已恢复的对象中引用导入的脚本

时间:2019-05-26 05:01:29

标签: javascript json angular

我有一个以字符串形式存储在其中的函数的json,当我使用新的Function恢复它并尝试使用恰好使用了由诸如lodash的angular导入的库的方法时,出现参考错误。这是ZombieLoader将恢复json对象的代码,在angular类测试中将尝试运行它,我将得到未找到的错误_。

// This class takes a json and produces an object with methods
export class ZombieLoader {
  static revive(st: string): object {
    const result = {};
    const obj = JSON.parse(st);
    for (const key of Object.keys(obj)) {
      if (key.startsWith('@')) {
        result[key.substring(1)] = new Function('return ' + obj[key])();
        continue;
      }
      result[key] = obj[key];
    }
    return result;
  }
}

// the json with function in string form that will be hydrated back for use
{
script: '{"@run":"function () { return _.chunk(['a', 'b', 'c', 'd'], 2); };}'
}  


// here I test the method which fails because it cant find _ 
import * as _ from 'lodash';
import {ZombieLoader} from './zombie-loader';

export class Test {
    constructor(script: string) {
         const sceneScript = ZombieLoader.revive(script);
         sceneScript.run();
    }
}

为什么重建的对象没有引用Angular加载的脚本,有一种方法可以重建对象并将其绑定到角度。 如果我将lodash添加到index.html文件中可以使用,但是我不想对其他几个库执行此操作

2 个答案:

答案 0 :(得分:1)

通过在末尾添加()-new Function('return ' + obj[key])()执行函数,它无法知道其调用方中的任何依赖关系。

我不知道run()在这里sceneScript.run();的作用,但是Function构造函数接受arguments参数,因此您可以传入所需的依赖项:new Function('_', 'return ' + obj[key]);并稍后调用函数从呼叫者那里传递来

sceneScript.run(_);

答案 1 :(得分:0)

由于Angular似乎没有加载_库,因为在创建组件时未直接使用_库。一个小的解决方案,尝试像这样在构造函数或Oninit中使用_库 console.log(typeof _ ); 这样您就不会得到参考错误。