Thursday 31 December 2020

How to import a service-like singleton-class with System.js?

I have a Singleton-Class FooService that is loaded via an import-map. I'd like to (a)wait for it and use it in various async functions like so:

declare global {
  interface Window {
    System: System.Module
  }
}

const module = window.System.import('@internal/foo-service')
const fooService = module.FooService

async function func1() {
  await fooService.doBar()
  .
  .
}

async function func2() {
  await fooService.doBar2()
  .
  .
}

But I could only get it to work like this:

declare global {
  interface Window {
    System: System.Module
  }
}

async function getfooService() {
  const module = await window.System.import('@internal/foo-service')
  return module.FooService
}

function func1() {
  getfooService().then(fooService => fooService .doBar())
  .
  .
}

function func2() {
  getfooService().then(fooService => fooService.doBar2())
  .
  .
}

How can I achieve this without loading it anew every time I want to use it?



from How to import a service-like singleton-class with System.js?

No comments:

Post a Comment