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

时间:2019-03-19 03:59:42

标签: angular angular-universal custom-element ssr

窗口小部件由自定义元素(@ angular / elements)制成,并嵌入通用角度中。我的操作方式是在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)

1 个答案:

答案 0 :(得分: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}));
       }
    }
  }

应该为您消除该错误。