![](/img/trans.png)
[英]Is it possible to run multiple apps with different angular versions on one page?
[英]Is it possible to use different angular elements built with different versions of 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);
});
}
}
在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 元素(Web 組件)並在 SPA 中使用。
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.