是否可以使用由不同版本的Angular构建的不同角度元素

问题描述 投票:1回答:1

我想知道是否可以使用以不同版本的Angular构建的不同角度元素(自定义元素)。我听说zone.js污染了全球范围。

感谢您的回答。

javascript angular web-component custom-element
1个回答
0
投票
已经说过,在一页上可以有100%的不同版本的多个角度元素。我们需要照顾的是只加载一次区域js,并在所有Web组件(Angular Elements)中共享它。

虽然引导了多个元素,但我们可以添加不加载/修补zonejs的逻辑(如果已经按如下所示加载:)

从polyfill.ts中删除所有Angular元素的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); }); } }

并且在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();

这样,我们绝对可以创建多个Angular Elements(Web组件)并在SPA中使用。

谢谢
© www.soinside.com 2019 - 2024. All rights reserved.