How to get singleton component (Aurelia 2)

Hi! I encapsulate my Aurelia 2 app in a web component (see below). MyApp component should be a singleton, and I would like to invoke one of its methods later on, thus I try to get it from the app’s container, but I end up getting a new instance that gets created.

import Aurelia from 'aurelia';
import { MyApp } from './my-app';

export class MyWebComponent extends HTMLElement {
  connectedCallback() {
    this.app = Aurelia.app({
      component: MyApp,
      host: document.querySelector('my-web-component'),
    });
    this.app.start();
  }

  myMethod() {
    this.app.container.get(MyApp).aMethod();
  }
}

customElements.define('my-web-component', MyWebComponent);

Please let me know if I got something wrong. I feel that the docs don’t help a lot on that.

Please consider that I am using ESNext.

Thanks!

Hi @frmjp! As the MyApp is your app root, you don’t need to use the container to grab the MyApp instance.

Instead, you can do this:

import { ICustomElementController } from '@aurelia/runtime-html';

(this.app.root.controller as ICustomElementController<MyApp>)
  .viewModel
  .aMethod()

Note that you can also explicitly register a singleton component. Refer the docs for details.

2 Likes