vci*_*ial 7 javascript web-component custom-element angular
我想知道是否可以使用不同版本的 Angular 构建的不同角度元素(自定义元素)。我听说 zone.js 正在污染全局范围。
感谢您的回答。
是的,你没听错。如果从特定版本创建的每个 angular 元素都试图加载 zonejs,我们就不能使用多个 angular 元素。
话虽如此,在单个页面上有 100% 可能有不同版本的多个角度元素。我们需要做的就是只加载一次 zone js 并在所有 web 组件(Angular Elements)中共享它。
在引导多个元素时,如果已经加载,我们可以添加不加载/修补 zonejs 的逻辑,如下所示:
从 polyfill.ts 中删除所有 Angular Elements 的 zonejs polyfill
在main.ts关卡中创建一个文件。假设 bootstraper.ts :
export class Bootstrapper {
constructor(
private bootstrapFunction: (bootstrapper: Bootstrapper) => void
) {}
/**
* Before bootstrapping the app, we need to determine if Zone has already
* been loaded and if not, load it before bootstrapping the application.
*/
startup(): void {
console.log('NG: Bootstrapping app...');
if (!window['Zone']) {
// we need to load zone.js
console.group('Zone: has not been loaded. Loading now...');
// This is the minified version of zone
const zoneFile = `/some/shared/location/zone.min.js`;
const filesToLoad = [zoneFile];
const req = window['require'];
if (typeof req !== 'undefined') {
req(filesToLoad, () => {
this.bootstrapFunction(this);
console.groupEnd();
});
} else {
let sequence: Promise<any> = Promise.resolve();
filesToLoad.forEach((file: string) => {
sequence = sequence.then(() => {
return this.loadScript(file);
});
});
sequence.then(
() => {
this.bootstrapFunction(this);
console.groupEnd();
},
(error: any) => {
console.error('Error occurred loading necessary files', error);
console.groupEnd();
}
);
}
} else {
// zone already exists
this.bootstrapFunction(this);
}
}
/**
* Loads a script and adds it to the head.
* @param fileName
* @returns a Promise that will resolve with the file name
*/
loadScript(fileName: string): Promise<any> {
return new Promise(resolve => {
console.log('Zone: Loading file... ' + fileName);
const script = document.createElement('script');
script.src = fileName;
script.type = 'text/javascript';
script.onload = () => {
console.log('\tDone');
resolve(fileName);
};
document.getElementsByTagName('head')[0].appendChild(script);
});
}
}
Run Code Online (Sandbox Code Playgroud)
在main.ts我们可以将引导程序逻辑更改为以下之一:
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { Bootstrapper } from './bootstraper';
const bootstrapApp = function(): void {
platformBrowserDynamic()
.bootstrapModule(AppModule)
.then(() => {})
.catch(err => console.error(err));
};
const bootstrapper = new Bootstrapper(bootstrapApp);
bootstrapper.startup();
Run Code Online (Sandbox Code Playgroud)
通过这种方式,我们绝对可以创建多个 Angular 元素(Web 组件)并在 SPA 中使用。
谢谢
| 归档时间: |
|
| 查看次数: |
1405 次 |
| 最近记录: |