我有一个 json,其中的函数以字符串的形式存储在其中,当我使用 new Function 恢复它并尝试使用碰巧使用像 lodash 这样的 angular 导入的库的方法时,我收到了一个引用错误。这是 ZombieLoader 将恢复 json 对象的代码,并且在 angular 类测试中将尝试运行它,我将收到错误 _ not found。
// 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 加载脚本的引用,有没有办法重建对象并将其绑定到 angular.js?如果我将 lodash 添加到 index.html 文件它可以工作,但我不想对其他几个库这样做
相关分类