首页 > 解决方案 > 如何在用作 Web 组件的 Angular 应用程序中延迟加载组件?(如何从正确的服务器加载块?)

问题描述

如何设置作为 Web 组件运行的应用程序,该应用程序必须从为 Web 组件提供脚本的服务器加载块,而不是尝试从刚刚提供包含 Web 组件的页面的服务器中延迟加载?

更详细的问题:

我的 Angular 应用程序中有一个LazytestComponent延迟加载的组件。

加载它的代码:

    const {LazytestComponent} = await import('../lazytest/lazytest.component');
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(LazytestComponent);
    const instance = this.lazyContainer.createComponent(componentFactory, undefined, this.injector);

Angular 为这个组件生成一个块,只有在这个惰性代码运行时才访问(networktab)。

这在使用 ng serve 运行应用程序时有效。

现在,通过使用 angular/elements 将其构建为 web 组件:

在@NgModule 中:

我们有:

  ngDoBootstrap() {
    const webComponent = createCustomElement(LazyApp, {injector: this.injector});
    customElements.define('lazyapp', webComponent);
  }

这也有效,我现在可以在另一台服务器上加载我的应用程序的 3 个脚本文件,并使用<lazyapp>-Tag 将其包含在页面中。

另一台服务器上的html页面:

<html>
<head>
    <script src="http://localhost:8089/lazy/polyfills.js"></script>
    <script src="http://localhost:8089/lazy/runtime.js"></script>
    <script src="http://localhost:8089/lazy/main.js"></script>
</head>
<body>
<lazyapp></lazyapp>
</body>
</html>

该网页从 localhost:8080 提供 - 角度应用程序从 localhost:8089 加载。

该应用程序作为 Web 组件加载,但在运行延迟加载时会失败。

它不是从“http://localhost:8089/lazy/317.js”加载块,而是尝试从“http://localhost:8080/317.js”加载它——这是服务于 html 页面的服务器,当然它不存在。

我怎样才能告诉我的应用程序可以找到它的块的 url?

标签: javascriptangularweb-component

解决方案


推荐阅读