我有一個 json,其中的函數(shù)以字符串的形式存儲在其中,當我使用 new Function 恢復它并嘗試使用碰巧使用像 lodash 這樣的 angular 導入的庫的方法時,我收到了一個引用錯誤。這是 ZombieLoader 將恢復 json 對象的代碼,并且在 angular 類測試中將嘗試運行它,我將收到錯誤 _ not found。// This class takes a json and produces an object with methodsexport 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 文件它可以工作,但我不想對其他幾個庫這樣做
Angular 中的新函數(shù)構造函數(shù)如何在恢復的對象中引用導入的腳本
喵喵時光機
2021-06-08 21:10:13