将自定义元素嵌入角度通用中时出错

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

该小部件由自定义元素(@ angular / elements)制成,并嵌入了通用的angular中。我的操作方式是在index.html中添加脚本标签(angularElements.js),并将自定义标签添加到组件中。

在有角度的非ssr模式下效果很好,但在ssr模式下会抛出异常。错误是自定义元素模块的构造函数被调用两次,并引发DOMException。

下面的代码是用于自定义元素的模块的示例代码。

declare var require: any;
@NgModule({

})
export class WidgetModule implements DoBootstrap {
  constructor(
    private injector: Injector,
    @Inject(PLATFORM_ID) private platformId: Object
  ) {

  }
  defineCustomElements(fn: any, name: string, component: Type<any>) {
    if ( isPlatformBrowser(this.platformId) ) {
      window.customElements.define(name, fn(component, {injector: this.injector}));
    }
  }
  ngDoBootstrap() {
    console.log('constructor of widget is called.....');
    if ( isPlatformBrowser(this.platformId) ) {
      const { createCustomElement }  = require('@angular/elements');

      this.defineCustomElements(createCustomElement, 'widget-main-schedule', MainScheduleComponent);
    }
  }
}

这是角度通用语言中的精巧代码。

<body>
  <app-root></app-root>
  <script type="text/javascript" src="http://localhost/widgets/angularElements.js"></script>
</body>
</html>

这是小部件示例

<div #main_schedule class="main-schedule">
      <h2>Competition Schedule</h2>
      <!-- this is widget -->
      <widget-main-schedule></widget-main-schedule>
    </div>

下面是浏览器控制台中的错误消息。

 ERROR DOMException: Failed to execute 'define' on 'CustomElementRegistry': this name has already been used with this registry
at CustomElementRegistry.e.(anonymous function) [as define] (http://localhost/widgets/angularElements.js:2:35267)
at t.defineCustomElements (http://localhost/widgets/angularElements.js:4:210330)
at t.ngDoBootstrap (http://localhost/widgets/angularElements.js:4:210525)
angular angular-universal custom-element server-side-rendering
1个回答
0
投票

我遇到了类似的问题,我的解决方案是在定义customElement之前进行检查。在您的代码中,将其更改为:

defineCustomElements(fn: any, name: string, component: Type<any>) {
    if ( isPlatformBrowser(this.platformId) ) {
       if (!window.customElements.get(name)) {  
          window.customElements.define(name, fn(component, {injector: this.injector}));
       }
    }
  }

应该为您消除该错误。

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