在 Angular 应用程序的销毁钩子中手动清除导入的脚本。以下是一个示例:
import { Component, OnDestroy } from '@angular/core';
import { ScriptService } from './script.service';
@Component({
selector: 'app-root',
template: 'Hello World
',
})
export class AppComponent implements OnDestroy {
constructor(private scriptService: ScriptService) {}
ngOnDestroy() {
this.scriptService.destroy();
}
}
在上面的示例中,AppComponent 实现了 OnDestroy 接口,并在其 ngOnDestroy 生命周期钩子中调用 ScriptService 的 destroy() 方法。ScriptService 中包含了逻辑来清理所导入的脚本。要创建 ScriptService,请使用以下代码:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class ScriptService {
private scripts: any = {};
constructor() {}
load(...scripts: string[]) {
const promises = [];
scripts.forEach((url) => {
if (!this.scripts[url]) {
this.scripts[url] = this.loadScript(url);
promises.push(this.scripts[url]);
}
});
return Promise.all(promises);
}
loadScript(url: string): Promise {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onload = () => {
resolve();
};
script.onerror = (error: any) => {
reject(error);
};
document.body.appendChild(script);
});
}
destroy() {
const scripts = document.getElementsByTagName('script');
for (let i = 0; i < scripts.length; i++) {
const script = scripts[i];
const src = script.getAttribute('src');
if (src && this.scripts[src]) {
script.remove();
delete this.scripts[src];
}
}
}
}
在上面的示例中,ScriptService 包含了 load() 方法,用于加载脚本,并且包含了 destroy()