我有一个名为employee-widget的小部件,此 employee-widget.js 文件位于我的Angular应用程序文件夹中(仅供src参考添加)。我正在按以下方式调用employee-widget.js,但未加载小部件。
选项1:
<div>
<h4>Calling employee widget</h4>
<script type="text/javascript" src="/src/assets/employee-app.0.1.0.js"></script>
<employee-widget></employee-widget>
</div>
注意:控制台日志中没有错误,仅显示“呼叫员工小部件”
选项2:
EmployeeContainer.ts
export class EmployeeContainerComponent implements OnInit {
constructor() {
console.log("Registration");
this.addWidget("/src/assets/employee-app.0.1.0.js");
}
ngOnInit() {}
addWidget(url: string) {
console.log("running registraion page");
const script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
document.body.appendChild(script);
const widget = document.createElement("employee-widget");
// The widgets element is a simple <div> with id="widgets"
const widgets = document.getElementById("widgets");
if (!widgets) {
return;
}
widgets.appendChild(widget);
}
}
employeecontainer.html
<div>
<h4>Calling employee widget</h4>
</div>
document.body.appendChild(script);行出错
*
component.ts:21 GET http://localhost:4400//src/assets/employee-app.0.1.0.js net :: ERR_ABORTED 404(未找到)
*
请在这里建议我做错了什么?
答案 0 :(得分:1)
在将项目构建到项目文件的同一位置后,资产文件夹将可用,因此您只需从路径中删除 src
export class EmployeeContainerComponent implements OnInit {
constructor() {
console.log("Registration");
this.addWidget("assets/employee-app.0.1.0.js");
}
ngOnInit() {}
addWidget(url: string) {
console.log("running registraion page");
const script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
document.body.appendChild(script);
const widget = document.createElement("employee-widget");
// The widgets element is a simple <div> with id="widgets"
const widgets = document.getElementById("widgets");
if (!widgets) {
return;
}
widgets.appendChild(widget);
}
}
第一个选项不起作用,因为您不能在组件模板的主体中包括script标签,因此您需要通过动态创建标签来使用第二个选项
答案 1 :(得分:1)
将以下内容添加到您的EmployeeContainer.ts
import "../../assets/employee-app.0.1.0.js";
如果没有解释 widget 是什么或者为什么要在Angular框架中使用它的原因,似乎没有必要做其他事情。