1

I am trying to load a configuration file from a server in an Angular 2 app, and as you can imagine it contains initialization parameters needed for the entire app, so it must be loaded first.

The problem is that JS is async by design, and so there is no way to make the app "wait" for the preference file. I already created a service which sends the request using an async AJAX request, but I have no idea on how to handle other parts asking this service "which is the value of this preference" when the cache is still not loaded. I can't reject requests, and I cannot block them, making them async would not work.

There should be a way to stop the app in a "loading" screen, I believe this is the correct way of doing it. While the app is in this mode the preferences are loaded, and then the UI is displayed.

The question: How do I defer the loading of the main component until the loading stage is finished? It would be nice to load a component which checks a series of requisites and initialize services (connectivity, settings, auth and so on), then load the main UI after they are all met.

John White
  • 917
  • 1
  • 12
  • 26

1 Answers1

1

In Angular2 Dart I use a Future to make it work; then whatever requires that property just has to await that value. See: https://www.dartlang.org/tutorials/language/futures

Future gatherNewsReports() async {
  // more slow code here
  String path =
      'https://www.dartlang.org/f/dailyNewsDigest.txt';
  return (await HttpRequest.getString(path));
}

Future printDailyNewsDigest() async {
  String news = await gatherNewsReports();
  print(news);
}

I believe you can do the same with Promises in JavaScript if you're not using Dart. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

async function printDailyNewsDigest() {
  var news = await gatherNewsReports();
  console.log(news);
}

Upon completion of the future / promise, trigger a URL change which can then load the required page.

JavaScript and Dart are SingleThreaded, if you block at any point, nothing will continue working.

Jan Vladimir Mostert
  • 12,380
  • 15
  • 80
  • 137