What is the best way to bring in a service as a singleton class using System.js?

I have a unique Singleton-Class FooService that is loaded through a special import-map. My goal is to efficiently await its loading and then utilize it in different asynchronous functions as shown below:

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()
  .
  .
}

However, I was only able to make it work using the following approach:

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())
  .
  .
}

If possible, how can I optimize this process without having to reload it every time I need to use it?

Answer №1

Your initial guess was close to being correct. It's important to note that the module returned by the import statement is a promise, so you must utilize it in the following manner:

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

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

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

Furthermore, I suggest avoiding the use of a FooService "module object" (or even worse, a class) and instead simply export named functions. This will allow you to eliminate the need for

.then(module => module.FooService)
.

Answer №2

If you want to encapsulate the code in an IIFE, you can do it like this:


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

// Encapsulate the rest of the code in an 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();
  }
})();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing an All-Routes-Except-One CanActivate guard in Angular2

In order to group routes within a module, I am aware that it can be done like this: canActivate: [AuthGuard], children: [ { path: '', children: [ { path: 'crises', component: ManageCrisesComponent }, ...

Locate the word or phrase without a comma

I am currently working on a code that involves finding keys with string values separated by commas. var db = { "name": "Nkosana", "middle": "Baryy", "surname": "walked", "batch_number": "test,b", "temp": ",,67,6,87,86,5,67865,876,67" ...

Missing Cookie in request using NodeJS and NextJS

Struggling with integrating cookies in a fullstack app I'm developing using Node for backend and NextJS for frontend on separate servers. The challenge lies in getting the browser to attach the cookie received in the response header from the node serv ...

JavaScript: Determining the point on a perpendicular line that is consistently a fixed distance away

I am currently working on finding a point that is equidistant from the midpoint of a perpendicular line. This point will be used to create a Bézier curve using the starting and ending points, along with this intermediate point. After calculating the perp ...

Retrieve the names contained within TD elements using the console

I always enjoy experimenting with new things. Take a look at the https://lodash.com/docs/4.17.15 lodash documentation site where you'll find a menu on the left side featuring all available functions. Is there a way to extract the names of these functi ...

What values are typically used in the "types" field of a package.json file?

As a newcomer in the realms of JS/TS, I am delving into creating an NPM package using TypeScript for educational purposes. To prepare the artifacts for registry upload, it's necessary to compile the TS files into JS files using the tsc command. Here i ...

Why is the background image not loading properly on first hover with CSS?

Whenever we load a page with a large image set as the background for a div, there seems to be a delay in displaying the image when we hover over the div. Is there a solution to this issue? I would prefer not to use a sprite image because I need to make alt ...

Managing time-intensive web service operations using JavaScript callbacks

One of the operations in my Web application involves a function that returns a value, which then needs to be passed to a web service method running separately from the application. This web service operation takes some time to complete and therefore must r ...

Ways to Retrieve the Text From the Selected Index in Datalist Element

I need to extract the inner text of the option tag using pure JavaScript This is the HTML code I am working with: <input list="in" name="i_n" class="form-control" placeholder="Enter Item Name" required> <datalist id="in" onChange="rate(this)"&g ...

What is the process to set a Woocommerce checkout field as optional when a checkbox is marked?

I need assistance with customizing the checkout page on Wordpress Woocommerce. Specifically, I want to make the field 'billing_name' not required if the checkbox 'buy_on_company' is checked. Currently, I have successfully hidden ' ...

What is the best way to fetch a UniqueID using document.getElementById()?

I am looking to utilize the __doPostBack JavaScript function. __doPostBack(obj.UniqueID,''); The challenge I'm facing is that I only have the ClientID of my object - ctl00_cpholder_myObjId document.getElementById("ctl00_cpholder_myOb ...

Initiating the Gmail React component for composing messages

Is it possible to use a React application to open mail.google.com and prefill the compose UI with data? This is a requirement that I need help with. ...

What is the best way to incorporate bullet points into a textarea?

How can I make a bullet point appear when pressing the 'enter' button inside a textarea? I tried using this code, but it doesn't seem to work. Any suggestions? <script> $(".todolist").focus(function() { if(document.getElementById( ...

Exploring Keypress events with Dojo's 'on' module

Recently, I've started utilizing Dojo's latest on module for event handling. It has been working well so far, but a new issue has cropped up. Specifically, when using the keypress event, I am unable to retrieve the character value (such as "2" or ...

Obtaining the source code from a different domain website with the help of jQuery

Is there a way to extract part of the source code from a YouTube page without using server-side programming? I've tried cross-domain AJAX techniques like Yahoo YQL and JsonP. While Yahoo YQL allows me to grab part of the source code, I'm facing ...

"Utilizing JQuery to enhance task management by implementing a delete function

I need help figuring out how to create a function that can delete tasks from my todo list. Currently, each task has its own remove button, but I want to implement a single remove button at the bottom that removes checked or crossed out tasks. Any suggestio ...

Utilizing the functionalities provided by node.js, I came across an issue and sought out a solution for the error message "TypeError: __WEBPACK_IMPORTED_MODULE_3_fs__.writeFile is not a function"

I have created a project centered around {typescript, react, electron, gaea-editor}. During an event, I utilized fs.writeFile() but encountered an error. The specific error message was: TypeError: __WEBPACK_IMPORTED_MODULE_3_fs__.writeFile is not a functi ...

Enhance your React Typescript High Order Component by incorporating additional properties and implementing them

I am in the process of creating a React HOC with specific requirements: It should take a component as input, modify the hidden property (or add it if necessary), and then return the updated component The rendered component should not display anything whe ...

Leveraging async/await within a React functional component

Just getting started with React for a new project and facing challenges incorporating async/await functionality into one of my components. I've created an asynchronous function called fetchKey to retrieve an access key from an API served via AWS API ...

I would greatly appreciate some guidance on asp.net and javascript

I am just starting out with JavaScript and facing some challenges. Currently, I'm struggling to develop a Mouseover and mouseout script. Here is my ASPX code: <div> <div id="div_img" style="height: 300px; width: 300px; border: solid 1p ...