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

冷暖自知 提交于 2021-01-28 11:20:14

问题


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?


回答1:


Your first guess was nearly fine. Notice that the module returned by import is a promise, so you need to use it as

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

async function func1() {
  (await fooService).doBar();
//^                ^
  …
}

async function func2() {
  (await fooService).doBar2();
//^                ^
  …
}

Btw I would recommend to avoid using a FooService "module object" (or worse, class) and instead just export named functions, so that you can drop the .then(module => module.FooService).




回答2:


you could try to wrap it in IIFE, like this:


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

// Wrap rest of the code in IIFE
(async () => {
  const module = await window.System.import("@internal/foo-service");

  // Use await keyword if FooService/doBar/doBar2 are async
  const fooService = await module.FooService;
  const doBar = await fooService;
  const doBar2 = await fooService;

  async function func1() {
    doBar();
  }

  async function func2() {
    doBar2();
  }
})();


来源:https://stackoverflow.com/questions/65293706/how-to-import-a-service-like-singleton-class-with-system-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!