假设我有一个 Angular 服务,该服务调用一个 servlet 请求包含我的自定义 JavaScript 函数的 library.js 文件。 有什么方法可以在运行时将这些函数动态添加到我的 Angular 应用程序中吗? 例如,在 library.js 文件中我可能有以下自定义函数:
helloWorld(){
alert("hello world");
}
它应该按如下方式工作:
1) 我使用标准的 Angular 模块 HttpClient 调用 servlet
2) servlet 发回 library.js,包含函数列表,如 helloWorld();
3) Angular Web 应用程序加载 library.js 文件(如何?)
4) 然后我可以在我的 Angular 代码中调用 helloWorld() 函数。
最佳答案
好的,我们可以通过以下方式解决问题:
1) servlet 响应以下消息,脚本标签是强制性的,否则它不会被识别为有效的 js 代码。
String servletAnswer = "<script type=\"text/javascript\">
function helloWorld(){
alert("custom message!");
}
</script>"
2) Angular 应用程序订阅并等待 servlet 以通常的方式回答。一旦我收到回复,我就会:
var script = response;
$('body').append(script); /* i append the script to body of the document,
now the function helloWorld is available to the application */
3) 我使用 eval 调用函数:
eval("helloWorld()");
希望对您有所帮助!谢谢大家
关于javascript - 将 javascript 函数动态添加到 Angular 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50046604/